简体   繁体   中英

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;

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.

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.

不,因为只有动态分配的内存可以泄漏(即使用malloc等人)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM