char pointer initialization in C

前端 未结 6 1240
情书的邮戳
情书的邮戳 2021-02-06 18:30

I am not so clear on character pointer and how they work.

The program builds, but crashes when I run it.

 char *ab = NULL;
 //ab = \"abc123\"; // works f         


        
6条回答
  •  爱一瞬间的悲伤
    2021-02-06 18:59

    You have allocated no memory to use with ab.

    The first assignment works because you are assigning to ab a string constant: "abc123". Memory for constant strings are provided by the compiler on your behalf: you don't need to allocate this memory.

    Before you can use ab with e.g. sprintf, you'll need to allocate some memory using malloc, and assign that space to ab:

    ab = malloc(sizeof(char) * (NUM_CHARS + 1));
    

    Then your sprintf will work so long as you've made enough space using malloc. Note: the + 1 is for the null terminator.

    Alternately you can make some memory for ab by declaring it as an array:

    char ab[NUM_CHARS + 1];
    

    Without allocating memory somehow for ab, the sprintf call will try to write to NULL, which is undefined behavior; this is the cause of your crash.

提交回复
热议问题