我目前正在处理一段代码,其中我们正在解析文件并使用不同的功能。通过使用printf
调用进行调试,我发现第二个malloc
调用遇到了内存错误。是什么导致第二个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;
}
答案 0 :(得分:2)
您正面临内存泄漏。 按照以下两个示例之一更正您的代码
是的,正如@Eugene_Sh所述,您应该为myToken->myChar
分配内存,并且不要忘记在释放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;
}