Ynv
Ynv

Reputation: 1974

Is this kind of string truncation in c causing memory leaks?

Will this leak memory?

char *str = "Hello/World";
char *pos = rindex(str, '/');
*pos = 0;

Upvotes: 2

Views: 131

Answers (3)

T.J. Crowder
T.J. Crowder

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

flolo
flolo

Reputation: 15526

No, as only dynamic allocated memory can leak (i.e. with malloc et. al.).

Upvotes: 0

ouah
ouah

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

Related Questions