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
You have allocated no memory to use with
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 = malloc(sizeof(char) * (NUM_CHARS + 1));
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
sprintf call will try to write to
NULL, which is undefined behavior; this is the cause of your crash.