简体   繁体   English

此C代码不断给我代码块中的分段错误

[英]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. puts函数期望一个char *指向一个字符串。 You're passing in an int instead. 您传递的是int 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. int的值被解释为一个指针,该指针可能未指向有效的内存位置,从而导致崩溃。

If you want to print an int , use printf instead with the %d format specifier. 如果要打印int ,请使用printf代替%d格式说明符。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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