ljustin ljustin -4 years ago 111
C Question

char pointer initialization in C

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 fine
sprintf(ab, "abc%d", 123); // this line seems to crash the program


I don't get how this can be wrong, when sprintf takes in a (char * str) as a first argument.

Can anyone please explain this to me?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download