0
int main()
{
    char* str;

    str = "string one";
    str = "string two";
    str = func();
    str = "string four";
    return 0;
}

char* func()
{
    char* tmp;

    tmp = "string three";
    return tmp;
}

I know str = "string one"; allocates memory for this string and assigns the address of that memory to str . by right the same thing should happen when str = "string two"; and str = func(); and str = "string four"; are executed, now I'm wondering how memory is handled in this situation. Does memory allocated to those strings release when new assignment happens or it's a form of memory leak?

sepisoad
  • 2,201
  • 5
  • 26
  • 37
  • 1
    Just for caution, do yourself the favor and take the habit to assign string literals only to variables that are declared `char const*`. String literals are not modifiable, so declaring them as you do may only bring you trouble. – Jens Gustedt Apr 12 '13 at 11:54
  • 1
    the difference: for str = "text"; memory is allocacated by the LINKER, with str = malloc(); YOU allocate the memory and are supposed to free(); the memory. – Peter Miehle Apr 12 '13 at 11:56

2 Answers2

3

There are no memory leaks in your code since it's not allocating anything. You only have string literals on the right-hand side of every assignment, and those don't need to be (and can't be) deallocated.

See "life-time" of string literal in C

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

No need to free this type of assignment. because they are allocated in stack(temp) memory only. If you have allocate memory using malloc(they are allocated in heap), you have to free

Mani
  • 17,549
  • 13
  • 79
  • 100