简体   繁体   English

为什么第二个 malloc 在这种情况下会失败?

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

I am currently working on a piece of code where we are parsing a file and working with different functions.我目前正在处理一段代码,我们正在解析文件并使用不同的函数。 Through debugging with printf calls, I have found that I am getting a memory error on the second malloc call.通过使用printf调用进行调试,我发现在第二次malloc调用中出现 memory 错误。 What could cause the second malloc to fail in this rough skeleton?什么可能导致第二个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;
}

You are facing memory leak.您正面临 memory 泄漏。 correct your code folowing one of the two samples bellow按照以下两个示例之一更正您的代码

and yes, as @Eugene_Sh mentioned, you should allocate memory for myToken->myChar and do not forget to free it before freeing myToken是的,正如@Eugene_Sh 提到的,您应该为myToken->myChar分配 memory 并且不要忘记在释放 myToken 之前释放它

SAMPLE 1 样品 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; }
SAMPLE 2 样品 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