2012-07-21 77 views
2

我做到以下幾點:如何在移動指針後釋放一些字節?

void * myFunction(void) { 
    void *someBytes = malloc(1000); 
    // fill someBytes 

    //check the first three bytes (header) 
    if(memcmp(someBytes, "OK+", 3) == 0) { 
     // move the pointer (jump over the first three bytes) 
     someBytes+=3 
    } 

    return someBytes; 
} 

接收器如何能夠釋放malloced指針? 當然我可以在指針上做-3。

但是這種情況下是否有最佳做法? 是否有在接收器功能仍然允許調用free(someBytes); 因爲someBytes還可以舉辦多種兆我想避免的memcpy一個簡單的解決方案(malloc(1000)是唯一的例子)。

+0

我相信你要找的是什麼'realloc' - 這樣一來,當你通過與數據你剛纔讀,您可以不斷調整分配的字節大小。雖然,您已經通過立即分配1000個字節來讓我們全部失敗。從它的聲音中,您實際上想要創建一個面向事件的流式閱讀器,由幾個情況組成。簡單地說:'tmp = read(3); if(memcmp(tmp,「OK +」,3)== 0){free(tmp); tmp = read(997);/*此處更多的條件測試* /} else {free(tmp); } - 只讀你所要的。 (除了嵌套if之外,它將是oop。) – 2012-07-21 14:45:08

回答

1

沒有任何辦法(除非你碰巧知道確切的偏移量)。最佳做法是存儲原始指針的副本,以便稍後使用它來釋放內存。

void* myFunction(void) { 
    void* someBytes = malloc(1000); 
    void* pos = someBytes; 
    // fill someBytes 

    //check the first three bytes (header) 
    if(memcmp(pos, "OK+", 3) == 0) { 
     // move the pointer (jump over the first three bytes) 
     pos+=3 
    } 

    return someBytes; 
} 
+0

這不會被編譯。但是,那麼OP的例子也不會。好吧。 – 2012-07-21 14:30:27

+0

是的..這是pseude /示例代碼。 :) – 2012-07-21 14:33:11

1

爲什麼不定義一個結構並讓你的函數分配並返回一個指針呢?

struct MyStruct { 
    PrivateHeader *header; 
    UserData* data; 
}; 

PrivateHeader是一個不透明的指針數據,只有myFunction知道如何訪問/操縱;您的功能的消費者只知道如何訪問/操作data

+0

也認爲,但我不能改變接收器的代碼。我需要檢查三個字節的頭並在三個字節後返回緩衝區,並確保接收者可以釋放緩衝區。我認爲唯一的辦法是memcpy(或memmov) – 2012-07-21 14:47:51

0

接收器是否也可以創建緩衝區?爲什麼myFunction會分配它不會刪除的內存?

void* myFunction(void) { 
    void* someBytes = malloc(1000); 

    return someBytes; 
} 

是有點相當於(功能)來:

size_t myFunction(void* someBytes, size_t size) { 
    // do something 

    if(memcmp(someBytes, "OK+", 3) != 0) { 
     return 0; // didn't find nuthin' 
    } 

    return how_many_bytes_myFunction_put_in_the_buffer; 
} 


void myCaller(void) 
{ 
    void* someBytes = malloc(1000); 

    size_t result = myFunction(someBytes, 1000); 

    // do something amazing 

    free(someBytes); 
} 
+0

是的。設計可能會更好......該函數需要創建並返回malloc塊(如X_init函數)。 – 2012-07-21 15:45:51

+0

@JonasSchnelli,爲什麼?誰刪除它?你在寫myFunction嗎?你在編寫調用myFunction的函數嗎?如果對最後兩個問題的答案是否定的,那麼你不能做AFAIK,但返回你指向的malloc。你可以嘗試做兩個讀取,一個獲得「OK +」和一個獲取數據。把數據放在你malloc的塊中。丟棄包含「OK +」的數據(這可能是堆棧中的簡單3字節數組)。 – 2012-07-21 15:51:21