簡體   English   中英

為什么第二個 malloc 在這種情況下會失敗?

[英]Why does the second malloc fail in this scenario?

我目前正在處理一段代碼,我們正在解析文件並使用不同的函數。 通過使用printf調用進行調試,我發現在第二次malloc調用中出現 memory 錯誤。 什么可能導致第二個malloc在這個粗略的骨架中失敗?

struct example {
    char *myChar;
    int myInt;
};

struct example *doThing(FILE *file) {
    struct example *myToken = (struct example *)malloc(sizeof(struct example));
    char buffer[32] = "";

    // other stuff

    if (strncmp(buffer, "random", 6) == 0) {
        strncpy(myToken->myChar, buffer, 6);
        myToken->tokenid = 1;
        return myToken;
    }

    return NULL; 
}

struct example *doThing2(FILE *file) {
    struct example *myOtherToken = (struct example *)malloc(sizeof(struct example));
    // other stuff
    return myOtherToken;
}

int main() {
    FILE *ofp = fopen("thefile.txt", "r");
    struct example *token1, *token2;

    token1 = doThing(ofp);
    token2 = doThing2(ofp);

    // other stuff

    free(token1);
    free(token2);
    return 0;
}

您正面臨 memory 泄漏。 按照以下兩個示例之一更正您的代碼

是的,正如@Eugene_Sh 提到的,您應該為myToken->myChar分配 memory 並且不要忘記在釋放 myToken 之前釋放它

樣品 1
 struct example* doThing(FILE *file) { char buffer[32] = ""; // other stuff if (strncmp(buffer, "random", 6) == 0) { struct example *myToken = (struct example *) malloc(sizeof(struct example)); myToken ->myChar= malloc(7); strncpy(myToken ->myChar, buffer, 6); myToken ->myChar[6]=0; myToken->tokenid = 1; return myToken; } return NULL; }
樣品 2
 struct example* doThing(FILE *file) { struct example *myToken = (struct example *) malloc(sizeof(struct example)); char buffer[32] = ""; // other stuff if (strncmp(buffer, "random", 6) == 0) { myToken ->myChar= malloc(7); strncpy(myToken ->myChar, buffer, 6); myToken ->myChar[6]=0; myToken->tokenid = 1; return myToken; } free(myToken ); return NULL; }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM