4

I was making some proves with strtol() from stdlib library because i had a program that always crashed and i found that this worked perfectly:

main(){
char linea[]="0x123456",**ap;
int num;
num=strtol(linea,ap,0);
printf("%d\n%s",num,*ap);
}

But when I added just a new declaration no matter where it crashed like this

main(){
char linea[]="0x123456",**ap;
int num;
num=strtol(linea,ap,0);
printf("%d\n%s",num,*ap);
int k;
}

just adding that final "int k;" the program crashed at executing strtol() can't understand why. I'm doing this on Code::Blocks

Zoe
  • 27,060
  • 21
  • 118
  • 148
Mark E
  • 3,403
  • 2
  • 22
  • 36

1 Answers1

10

You get a crash because you are passing strtol an uninitialized pointer, and strtol dereferences it. You do not get a crash the first time by pure luck.

This will not crash:

main() {
    char linea[]="0x123456", *ap;
    int num;
    num = strtol(linea, &ap, 0);
    printf("%d\n%s", num, ap);
    int k;
}
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thanks it did work! But about the luck i don't think so, it happens every time if i added any other variable it crashed, no new variable never crashed But thank you really much – Mark E May 18 '12 at 01:11
  • 4
    @MarkE By "luck" I mean that since it is an undefined behavior, the crash is not necessarily going to happen. When you declare an extra variable, you change the layout of your automatic variables on the stack, so the illegal write that used to cause a crash with one stack layout would not cause a crash with another stack layout. If you're not on windows, try using valgrind with your old program, it should pinpoint the problem even when there is no crash. – Sergey Kalinichenko May 18 '12 at 01:15