Freeing strings in C

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

    Simple answer yes,no. Also your code is buggy.

    Concrete answer:

    char *a=malloc(sizeof(char)*4);
    

    You allocate memory so you should free it.

    a="abc";
    

    This assigns a pointer to a constant string to your char* a, by doing so you loose the pointer to the memory allocated in the first line, you should never free constant strings.

    Use strcpy(a,"abc"); instead of a="abc"; to move the string into your allocated memory.

提交回复
热议问题