Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

weird crash with strtol() in C

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

like image 608
Mark E Avatar asked Dec 28 '22 00:12

Mark E


1 Answers

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;
}
like image 187
Sergey Kalinichenko Avatar answered Dec 31 '22 01:12

Sergey Kalinichenko