printf crashes after successful printing

1.1k Views Asked by At

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.

2

There are 2 best solutions below

7
Govind Parmar On BEST ANSWER

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:

  1. Explicitly initialize the last element of your string array to be NULL so that the loop will actually know to stop at the end.
  2. Instead of incrementing the pointer, increment the offset at which you dereference it with a loop counter variable.

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;
}
0
Ville Miekk-oja On

I commented out code that comes after the use of this function. This resulted into fully successful run of the code. So apparently, the execution order of the code wasn't linear in a way that it would execute line after line. But after the last *array print it tried to execute code that was coming after the function. Now when I commented out that code, the function works like a charm.

Those who are interested, the code I commented out related to freeing memory from the *arrays.