简体   繁体   中英

Does the equal sign reallocate memory in a char *?

If i use the following code char * foo = "words" . Should i call free() before i do : foo = "two words"; . How does this assignemnt work? Is the memory containing the string "word" freed , then enough memory to hold the string "two words" then allocated and then foo set to point to the new string. I just want to make sure my code is as efficient as possible and without any mem leaks .

No, you should only call free for an object that you have allocated through malloc , calloc or realloc .

"words" is an object with static storage duration and you cannot free the object.

No need to call free() . In fact, it would fail. String constants declared like this are not on the heap and will exist for the life of your program regardless.

Call free() on memory that your program allocates using malloc() , etc.

If i use the following code char * foo = "words" . Should i call free() before i do : foo = "two words"; .

No. Argument to free must be a pointer previously returned by either malloc , calloc or realloc functions. Otherwise it will invoke undefined behavior .

How does this assignment work?

When compiler encounters a string literal of length n , it sets aside n+1 bytes of memory for the string. A char pointer points to the first byte of allocated memory when the string literal is assigned to it.

Once stored in memory, string literals are available for the lifetime of the program.
If you assign "two words" latter to foo , then still word will continues to stored at that section, but this section is different from the location allocated by 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