char* get_string() {
char * a = malloc(sizeof(char)*5);
a = "asdf";
return a;
}
Can someone please explain why this function would cause memory leak?
char* get_string() {
char * a = malloc(sizeof(char)*5);
a = "asdf";
return a;
}
Can someone please explain why this function would cause memory leak?
You first initialized a with a pointer to a location in memory. Then you re-assign a to another pointer to location occupied by string asdf, so you lost the first pointer to the allocated memory. you can never free them since you lost track of the 5 bytes memory allocated by malloc initially.
You leak that 5 bytes of memory here.
If you want to copy asdf to the memory pointed by a, you can use strcpy.
strcpy(a, "asdf");
In this way, you need to call free in your code somewhere to avoid leaks.
Short answer:
char * a = malloc(sizeof(char)*5);
you allocated memory here from the heap, a has an address in the heap (say 0x1234EEEE) pointing into dynamic memory. You need to free this allocation when done, else a memory leak happens.
then
a = "asdf";
now you have assigned a as pointing to static compile time memory location where the string "asdf" is stored (say 0x0BADBEEF, it's not in the dynamic heap). You no longer know where the hell you allocated memory from the malloc call above (it was at 0x1234EEEE, but now you have no reference to it), therefore you can never free() it ... that's a leak;
"char *a;"
a here is a pointer, it can point to anything.
"a = (char *)0x0000" should be valid, but not logical;
"long l = 12345L; a = (char *)&l;" this should be legal also, but not logical
"asdf" is a static string in your example, it is stored in compile time allocated memory. You can just "return("asdf");" from your function, understanding it is in a statically allocated memory space defined at compile time. Working with pointers without understanding logical memory layouts will have ramifications you may soon learn ;~).