简体   繁体   中英

This C code keeps giving me a segmentation fault in codeblocks

This a problem I keep trying to fix, but fail. Why do you think it is so?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

        int main(void)
    {
        char str[500];
        sprintf(str, "int cube = %i;", 29);
        char *ptr;
        strtok_r (str, "=", &ptr);
        printf ("'%s'  '%s'\n\n", str, ptr);
        char temp[500];
        sprintf(temp, "%s", ptr);
        int conditional = atoi(temp);
        puts(conditional);
        return 0;
        }

The problem is here:

puts(conditional);

The puts function expect a char * which points to a string. You're passing in an int instead. This is undefined behavior.

The value of that int is being interpreted as a pointer which probably doesn't point to a valid memory location, causing the crash.

If you want to print an int , use printf instead with the %d format specifier.

printf("%d\n", conditional);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM