Reputation: 1974
Will this leak memory?
char *str = "Hello/World";
char *pos = rindex(str, '/');
*pos = 0;
Upvotes: 2
Views: 131
Reputation: 1074979
No, for two reasons: The main reason being that the contents of an allocated block don't matter, what matters is freeing any blocks you allocate. The second reason in this specific case is that you're writing to a block of memory that wasn't dynamically allocated by the code in the first place (which may result in undefined behavior).
Illustrating the first point, let's actually allocate some memory dynamically:
char *str = strdup("Hello/World"); // Allocates a block of memory and copies the string into it
char *pos = rindex(str, '/'); // Finds the slash
*pos = 0; // Terminates the string
free(str); // Releases the block
The fact we wrote a string terminator to the middle of the block is irrelevant, when we free the memory, the entire block is released.
Upvotes: 4
Reputation: 15526
No, as only dynamic allocated memory can leak (i.e. with malloc et. al.).
Upvotes: 0
Reputation: 145899
No, but this will invoke undefined behavior as you are writing to a string literal. String literals are not required to be modifiable in C.
Upvotes: 7