【问题标题】:This C code keeps giving me a segmentation fault in codeblocks此 C 代码不断给我代码块中的分段错误
【发布时间】:2016-12-22 21:35:59
【问题描述】:

这是我一直试图解决的问题,但失败了。为什么会这样?

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

【问题讨论】:

  • 请展示您迄今为止的研究/调试工作。请先阅读How to Ask页面。
  • 使用strtok_r的返回值。
  • puts(conditional); --> printf("%d\n", conditional);

标签: c string split segmentation-fault runtime-error


【解决方案1】:

问题出在这里:

puts(conditional);

puts 函数需要一个指向字符串的char *。您正在传递 int 。这是未定义的行为。

int 的值被解释为可能没有指向有效内存位置的指针,从而导致崩溃。

如果您想打印int,请使用printf 代替%d 格式说明符。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-23
    • 2013-10-20
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多