weird crash with strtol() in C

1.2k views Asked by At

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

1

There are 1 answers

2
Sergey Kalinichenko On BEST ANSWER

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;
}