[英]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 之前释放它
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.