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?
In C, a string can be referred to either using a character pointer or as a character array.
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.
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.
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.
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()
.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With