Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
user3003873 Avatar asked Feb 14 '17 09:02

user3003873


People also ask

Can char pointer store string?

In C, a string can be referred to either using a character pointer or as a character array.

What is a memory leak and how would you avoid it?

Memory leak occurs when programmers create a memory in heap and forget to delete it. The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory.

How is a string literal stored in the memory?

The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.

What is char in string literal?

1) character string literal: The type of the literal is char[N], where N is the size of the string in code units of the execution narrow encoding, including the null terminator. Each char element in the array is initialized from the next character in s-char-sequence using the execution character set.


2 Answers

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().

like image 132
P.P Avatar answered Sep 23 '22 03:09

P.P


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).

like image 40
Jean-François Fabre Avatar answered Sep 23 '22 03:09

Jean-François Fabre