Freeing strings in C

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

    You've got a memory leak here. When you set a="abc", you're not filling the memory you just allocated, you're reassigning the pointer to point to the static string "abc". b points to the same static string.

    What you want instead is strncpy(a, "abc", 4), which will copy the contents of "abc" into the memory you allocated (which a points to).

    Then you would need to free it when finished.

提交回复
热议问题