[英]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.