2017-03-26 23 views
-2
size_t writeFunctionHandler(char *contents,size_t size,size_t nmemb,void *userdata) { 
    // size of the storedSize 
    static size_t storedSize = 0; 

    // the size of data available 
    size_t realSize = size * nmemb; 

    char *dataBuffer = (char *) userdata; 

    // realloc the buffer buffer 
    dataBuffer = realloc(dataBuffer,storedSize + realSize); 

    if (dataBuffer == NULL) { 
    printf("Could not allocate memory \n"); 
    return 0; 
    } 

    // store the contents of realSize from last storedSize 
    memcpy(&(dataBuffer[storedSize]),contents,realSize); 

    storedSize += realSize; 
    return realSize; 
} 

我不明白,爲什麼被realloc'd 指針上面的代碼返回值和錯誤沒有被分配指針被realloc'd沒有被分配

當我使用此示例代碼

struct MemoryStruct { 
    char *memory; 
}; 

size_t writeFunctionHandler(char *contents,size_t size,size_t nmemb, void *userdata) { 
    size_t realSize = size * nmemb; 
    static size_t storedSize = 0; 
    //char *dataBuffer = (char *)userdata; 
    struct MemoryStruct *chunk = (struct MemoryStruct *)userdata; 

    printf("print 1\n"); 
    chunk -> memory = realloc(chunk -> memory,storedSize + realSize); 
    printf("print 2\n"); 

    if (chunk -> memory == NULL) { 
    printf("Could not allocate memory\n"); 
    return 0; 
    } 

    memcpy(&(chunk -> memory[storedSize]),contents,realSize); 
    storedSize += realSize; 
    printf("print 3\n"); 

    return realSize; 
} 

所有似乎工作正常罰款。

上面這是一個捲曲writeFunctionHandler

int main() { 
    char *buffer = calloc(1,1); 
    // struct MemoryStruct chunk; 
    // chunk.memory = calloc(1,1); 

    CURL *curl = curl_easy_init(); 

    curl_easy_setopt(curl, CURLOPT_URL, "http://stackoverflow.com"); 
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunctionHandler); 
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)buffer); 
    // curl_easy_setopt(curl,CURLOPT_WRITEDATA, (void *) &chunk); 

    free(buffer); 
    //free(chunk.memory); 
    curl_easy_cleanup(curl); 

    return 0; 
} 

我不明白,我在後一種情況下使用2代碼之間有什麼區別,除了事實struct

+0

你確定** sample **函數在最後一個'curl_easy_setopt'和'free(chunk.memory)'之間沒有任何東西嗎? – StoryTeller

+0

@StoryTeller這裏的實際代碼如何看起來像https://gist.github.com/anonymous/9274da0998124dc9576f28e52327af87 – Ratatouille

+0

對不起,但你給的鏈接只是一個404 – StoryTeller

回答

3

問題是,userdata指向包含成員memory的結構,它是從堆中分配的成員。

此外,函數返回時,memory可能已被realloc更改,但是在您的版本中,更改無法在函數外部看到。這是因爲指針的已通過,而不是地址。如果地址通過了(即void **userdata),那麼你就可以接收到該地址(即*userdata= realloc(..),並且它將在該函數外面顯示出來。

相關問題