gpt4 book ai didi

c - 分段故障错误(核心已转储)

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:42 25 4
gpt4 key购买 nike

我在下面的代码中遇到了 Segmentation fault (core dumped) 错误。

请指出我哪里出错了?

#include "string.h"
int main(){
char *str=NULL;
strcpy(str,"something");
printf("%s",str);
return 0;
}

http://codepad.org/Wo9dIcnK

我正在浏览一个网站,在那里我看到了这个问题并尝试编译代码。它说预期的输出应该是(空)。这是链接 cquestions.com/2010/10/c-interview-questions-and-answers.html第13题最后一个例子

最佳答案

在将字符串复制到它之前,您需要为 str 分配内存。

char *str = malloc(10) // Length of string "Something" + 1  

请注意,在将 NULL 分配给 str 之后,它指向任何地方都是 c-faq说:

[...] a null pointer points definitively nowhere; it is not the address of any object or function.

如果 str 不是任何对象的地址,那么怎么可能将任何内容复制到它?

关于c - 分段故障错误(核心已转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24211780/

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