简体   繁体   中英

Memory leak when initialise string

Case 1 : I have written following c program and when I checked for memory leak I got memory leakage at this line str = (char*)malloc(10); even when I have written statement to free that memory

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *str;
    str = (char*)malloc(10);
    str = "string";
    printf("length : %ld\n",strlen(str));
    free(str);
    return 0;
}

Case 2:

When I replaced str="string" with strcpy() there is no any leak why it is so?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char *str;
    str = (char*)malloc(10);
    strcpy(str,"string");
    printf("length : %ld\n",strlen(str));
    free(str);
    return 0;
}

str = "string";

After this str points to different memory location(on many platforms it will be read only memory). So it no longer points to memory that you allocated via malloc . When you call free(str) you are trying to free some memory that you aren't suppose to. This is an undefined behavior. It may do nothing, or it may crash. And the malloced memory is being leaked.

strcpy(str,"string");

Here the string is copied to already allocated memory pointed by str . You own this memory, you copied data to it and then you free it. So there is no problem here.

So the basic difference between the two cases is that in first case str points to a different location than the allocated one.

Both are not same.

In this case, strcpy(str, "string") is correct way to copy the "string" to str. str is allocated then you free it. so no memory is leaking.

In case of str = "string" , memory allocated to str will lost and it will cause memory leak.

 str = (char*)malloc(10);
 str = "string"; <-- You just lost the pointer to the malloced memory. ie. memory leak.
 free(str); <-- Here you are trying to free the `"string"` itself. Not possible.

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