简体   繁体   中英

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. What could cause the second malloc to fail in this rough skeleton?

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. 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

SAMPLE 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
 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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM