gpt4 book ai didi

c - 为什么 printf 会导致段错误?

转载 作者:行者123 更新时间:2023-12-04 04:39:15 25 4
gpt4 key购买 nike

关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

7年前关闭。



Improve this question




我有这个代码:

char* env;

if (getenv("MP") == NULL)
{
env = "/usr";
}
else
{
env = getenv("MP");
}

printf("($MP is %s)\n", env);
printf("The program seg faults without printing me :(");

如果未设置 $MP 环境变量,则程序在第一次打印后出现段错误。如果设置,则没有段错误并且一切正常。

最佳答案

如果我不包括 stdlib.h,我可以让你的程序出现段错误

即试试这个:

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

int main(void)
{
char* env;

if (getenv("MP") == NULL)
{
env = "/usr";
}
else
{
env = getenv("MP");
}

printf("($MP is %s)\n", env);
printf("The program seg faults without printing me :(");

return 0;
}

关于c - 为什么 printf 会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19189644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com