When to use malloc for char pointers

前端 未结 5 912
醉话见心
醉话见心 2020-12-23 00:19

I\'m specifically focused on when to use malloc on char pointers

char *ptr;
ptr = \"something\";
...code...
...code...
ptr = \"something else\";
5条回答
  •  抹茶落季
    2020-12-23 00:47

    malloc is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:

    char *literal = "foo";
    

    However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc:

    char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
    // ...
    free(buf);
    

提交回复
热议问题