When to use malloc for char pointers

前端 未结 5 902
醉话见心
醉话见心 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:45

    As was indicated by others, you don't need to use malloc just to do:

    const char *foo = "bar";
    

    The reason for that is exactly that *foo is a pointer — when you initialize foo you're not creating a copy of the string, just a pointer to where "bar" lives in the data section of your executable. You can copy that pointer as often as you'd like, but remember, they're always pointing back to the same single instance of that string.

    So when should you use malloc? Normally you use strdup() to copy a string, which handles the malloc in the background. e.g.

    const char *foo = "bar";
    char *bar = strdup(foo); /* now contains a new copy of "bar" */
    printf("%s\n", bar);     /* prints "bar" */
    free(bar);               /* frees memory created by strdup */
    

    Now, we finally get around to a case where you may want to malloc if you're using sprintf() or, more safely snprintf() which creates / formats a new string.

    char *foo = malloc(sizeof(char) * 1024);        /* buffer for 1024 chars */
    snprintf(foo, 1024, "%s - %s\n", "foo", "bar"); /* puts "foo - bar\n" in foo */
    printf(foo);                                    /* prints "foo - bar" */
    free(foo);                                      /* frees mem from malloc */
    

提交回复
热议问题