ImNoob
ImNoob

Reputation: 145

c programming segfault unitialised int?

I have this c program that looks like.

int indexLength;
char *args[1024];
while(args[indexLength])
     indexLength++;

If i run the program under computer at work, the while loop line gives me a segfault..and the indexLength take some ridiculous arbitrary value. But if i run the program on a linux machine at home, there are no segfault and my program run normally.

The only difference i can think of between the 2 machine is that the one at work has gcc4.7 redhat version, and is running Fedora OS, and my machine at home has gcc4.7 downloaded from ppa repository, and is running ubuntu OS. But, i'm not convinced that's the only difference! What can it be?

EDIT: sorry i forgot to mention. The segfault went away on the computer at work if i initialise indexLength = 0..

Upvotes: 1

Views: 103

Answers (2)

simonc
simonc

Reputation: 42205

Your code invokes undefined behaviour

  • args is uninitialised so each element contains unpredictable values. Maybe you'll find a NULL pointer in the next 4k of stack and exit the loop; maybe you won't and you'll read beyond the end of the array
  • indexLength is uninitialised so you may read way beyond the end of your array immediately
  • the effect of reading beyond the end of args is also unpredictable. This includes potentially crashing, say if you don't find a zero word before you reach the limits of readable memory for your process

Despite initial appearances, setting indexLength=0 didn't actually make your code safe. You're still reading uninitialised memory so are relying on finding a NULL element inside args. There is no way to guarantee that you'll find this. If your loop doesn't exit before you reach the end of your array, you're back into undefined behaviour so your program may crash on any further iteration.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

Reading from uninitialized memory is undefined behavior. Variables are not initialized by default, so indexLength can take any value until you assign it. Since the behavior is undefined, the program could run on some machines, and crash on others.

Moreover, even initializing the indexLength to zero does not fix undefined behavior, because args remains uninitialized. This means that the program may not stop upon reaching the end of the array, and access values past the end of the allocated region. Of course in order to do that all values in the array of 1024 items must be non-zero, so the odds are in favor of stopping before reaching the end of the array. However, in order to fix this undefined behavior you need to check the index before accessing values.

Upvotes: 5

Related Questions