分段错误错误(核心转储)

时间:2014-06-13 18:30:54

标签: c pointers segmentation-fault

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

请告诉我哪里出错?

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

http://codepad.org/Wo9dIcnK

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

3 个答案:

答案 0 :(得分:6)

在将字符串复制到str之前,您需要为char *str = malloc(10) // Length of string "Something" + 1 分配内存。

NULL

请注意,在将str分配给str后,它会指出c-faq所说的无处:

  

[...]空指针明确指出无处;它不是任何对象或功能的地址。

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

答案 1 :(得分:2)

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int main(){
    int size = 10;
    char *str=NULL;
    str=malloc(size);
    strcpy(str,"something");
    printf("%s", str);

}

缩进代码也很重要:$

答案 2 :(得分:-1)

你可以使用malloc或strdup。

相关问题