Home > Back-end >  Memory leak in c due to the malloc
Memory leak in c due to the malloc

Time:04-08

I am getting the memory leak due to first malloc call. I tried to comment out and free but there is no way that I can fix it. The code wants to parse the query than put the information inside the map. At the same time it is going to update struct too


   
        row_ = atoi(strtok(NULL,",:"));
        col_ = atoi(strtok(NULL,",:"));
       
    }
}

CodePudding user response:

For starters this for loop

for(int j = 0; j < strlen(query); j  ){
    if(!strcmp(&query[j], ",")){
        count  ;
    }
}

does not make a sense. It seems you mean instead

for(int j = 0; j < strlen(query); j  ){
    if( query[j] == ',')){
        count  ;
    }
}

You allocated memory and its address is assigned to the pointer type.

char* type = malloc(sizeof(char *));
//      char* char_name= (char *)malloc(1);

then the pointer was reassigned

type = strtok(query, ",:");

So the address of the allocated memory is lost and you have a memory leak.

This commented declaration

char* char_name= (char *)malloc(1);

also invokes a memory leak due to the statement

char_name = strtok(NULL,",:");

This statement

char_name = realloc(char_name, sizeof(char_name) 1);

does not make a sense at least because sizeof( char_name ) is equivalent to sizeof( char * ). It seems you mean at least

char_name = realloc(char_name, strlen(char_name)   2 );

But in any case you may not reallocate the memory using the pointer because it does not point to a dynamically allocated memory after this statement

    char_name = strtok(NULL,",:");

CodePudding user response:

examine these 2 lines of code

    char* type=malloc(sizeof(char *)); <<<<<<=======
    //      char* char_name= (char *)malloc(1);
    int row_,col_;
    int count =0;

    for(int j=0;j<strlen(query);j  ){
            if(!strcmp(&query[j],",")){
                    count  ;
            }
    }
    count=(count 1)/3;

    type = strtok(query, ",:");   <<<<<<=======

You malloc some memory, do nothing with it and then overwrite the pointer. So now there is no way to free it or use it.

As far as I can see you just need

 char*type = NULL;

and take out the frees of type too

Note - I have not verified the rest of the code. just answered your leak question. THe way you are using strok is certainly not idiomatic. And I suspect that you think

 type = strtok(query, ",:");

copies the first token into the buffer pointed at by type. It does not, what you need is this

 type = strdup(strtok(query, ",:"));

likewaise the assignments in the loop

      char_name = strtok(NULL,",:");
    char_name = realloc(char_name, sizeof(char_name) 1);

is very wrong. YOu cannot realloc the return of strtok. Again you need

    char_name = strdup(strtok(NULL,",:"));
  • Related