Freeing strings in C

前端 未结 6 1518
忘掉有多难
忘掉有多难 2021-02-03 11:26

If I would write:

char *a=malloc(sizeof(char)*4);
a=\"abc\";
char *b=\"abc\";

do I need to free this memory, or is it done by my system?

6条回答
  •  失恋的感觉
    2021-02-03 11:42

    In your situation you won't have any way to free the dynamic allocated memory because you are losing the reference to it.

    Try this out:

    #include 
    #include 
    
    int main()
    {
      char *a=(char*)malloc(sizeof(char)*4);
      printf("Before: %p\n",a);
      a = "abc";
      printf("After: %p\n",a);
      free(a);
      char *b = "abc";
    
      return 0;
    }
    

    You will obtain

    Before: 0x100100080
    After: 0x100000f50
    

    You will see that the two pointers are different. This because the string literal "abc" is placed into data sector of the binary files and when you do

    a = "abc"
    

    you are changing the pointer of a to point to the constant literal string "abc" and you are losing the previously allocated memory. Calling free on a is not correct anymore, just because it won't point to a valid dynamically allocated address anymore. To preserve the pointer and be able to free it you should copy the string with

    strncpy(a, "abc", 4)
    

    This will effectively copy characters from the literal to the dynamically allocated method, preserving the original pointer.

提交回复
热议问题