Language is C. I have an array of char* types (char *array[] / char** array) as function argument, and I want to print them all to separate lines like this:
while (*array) {
printf("%s\n", *array);
printf("after last print");
array++;
}
Now for some reason, with a certain input, it manages to print all the values, but immediately crashes after the last *array is printed. So after the last printf, it doesn't print the "after last print" anymore. Unfortunately, I'm on Windows 7 with netbeans C support, without gdb. There were some problems when I tried to install it to netbeans, but that's another story.
First of all, what could be causing this? Secondly, how could I without gdb try to debug this behaviour best? If one provides an answer that helps me to debug the problem and that way solve it, I will grant points from that alone too. Some background information related to the function argument that causes the crash: I used strtok to generate char** arr from char* string, where a space was used as the delimeter.
EDIT:
Some more information: If I inside that same function try to printf the last *array, it works fine, and the program continues normally. So this works:
printf("%s\n", array[4]);
The last index before NULL happens to be 4 in my test case. But then when that same thing is done inside the loop like seen before, it does manage to printf it, but crashes right away after, not printing the second line anymore.
If you don't explicitly initialize the last element of your string array to be null, it's going to be an uninitialized (i.e. wild pointer), so when you dereference it in printf
it will crash.
Things to do:
This code works just fine for me and doesn't crash:
#include <stdio.h>
char *array[] = { "Hello", "World", "My", "Name", "Is", "Govind", "Parmar", NULL } ;
int main()
{
int i;
for(i = 0; *(array+i); i++)
{
printf("%s\n", *(array+i));
}
printf("after last print\n");
return 0;
}