user3003873
user3003873

Reputation: 553

Does making a char* point to another string literal leak memory?

I Have some misunderstanding regarding this simple example:

char *s = "abc";
s = "def";

Will the assignment of the second string cause a memory leak, or it will be replaced properly? If the former is true, how do I replace the value of s the right way?

Upvotes: 8

Views: 1268

Answers (3)

RoadRunner
RoadRunner

Reputation: 26315

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.

Upvotes: 0

P.P
P.P

Reputation: 121407

No. There's no memory leak.

You have simply changed s to point to a different string literal which is fine (with this: s = "def";).

Put simply, if you haven't allocated anything yourself using malloc/calloc/realloc or any function that returns a dynamically allocated memory (and documentation tells you to free(). For example, POSIX's getline() function does that), you don't need to free().

Upvotes: 9

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

Both strings are defined statically so there's no memory leak. What would leak would be:

char *s = strdup("abc");  // dynamic memory allocation
s = "def";

Actually there's a small static memory waste (wouldn't call that a leak) since you're not able to use "abc" anymore.

But since it cannot be repeated even by calling the routine where your code is located, I definitely wouldn't call that a leak.

Now if you have char s[] = "abc"; (array, not pointer), and a "def" string of equal size, you could do:

strcpy(s,"def");

to replace the contents of the string (but don't do that on a statically assigned pointer like defined your code: undefined behaviour).

Upvotes: 6

Related Questions