Your code segment:
char *s = "abc";
s = "def";
will not cause a memory leak. char *s
is a pointer in memory. When you use char *s = "abc"
, you set a string literal that *s
can point to. When you set s
to the string literal "def"
, all you are doing is changing where *s
points to.
Note: You can only do this with pointers, and not arrays. If you want to use arrays instead, you may need to use strcpy(3)
/ strncpy(3)
.
Since you haven't allocated any pointer, either with malloc(3)
/strdup(3)
, it is difficult to get a memory leak.
However, here is an example of a memory leak:
const char *str1 = "abc";
const char *str2 = "def";
char *s1 = malloc(strlen(str1)+1); /* dynamic memory allocation with malloc() */
char *s2 = malloc(strlen(str2)+1);
s1 = s2;
Here you set s1
to s2
. Therefore, this means the memory location of s1
does not exist anymore, as s1
is pointing to s2
, and not the original memory location it was allocated. You can no longer deal-locate this pointer using free(3)
, as their is no longer a reference to its location. If you never free()
a pointer allocated on the heap, that will also cause a memory leak.