Freeing strings in C

前端 未结 6 1521
忘掉有多难
忘掉有多难 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:43

    You cannot assign string in this way with C

    a = "abc"
    

    However if you use malloc then you have to use free, like this

    free(a);
    

    But pay attention if you use free(a) in your example you get an error. Because after the malloc you change the pointer a value to the static string "abc"; So the next free(a) try to free a static data. And you get the error.

提交回复
热议问题