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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With