简体   繁体   English

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

[英]Segmentation fault error (core dumped)

I am getting Segmentation fault (core dumped) error in below code. 我在下面的代码中遇到Segmentation fault (core dumped)错误。

Please suggest where I am going wrong? 请指出我要去哪里错了?

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

http://codepad.org/Wo9dIcnK http://codepad.org/Wo9dIcnK

I was going through a site where I saw this problem and tried to compile the code. 我正在浏览一个发现此问题并尝试编译代码的站点。 It says expected output should be (null). 它说预期输出应为(空)。 Here is the link cquestions.com/2010/10/c-interview-questions-and-answers.html 13th question last example 这是链接cquestions.com/2010/10/c-interview-questions-and-answers.html第13个问题的最后一个示例

You need to allocate memory for str before copying string to it. 您需要在为str复制字符串之前为其分配内存。

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

Note that after assigning NULL to str , it points nowhere as c-faq says: 请注意,在为str分配NULL之后,它没有指向c-faq所说的任何地方:

[...] a null pointer points definitively nowhere; [...]空指针肯定无处指向; it is not the address of any object or function. 它不是任何对象或函数的地址。

If str is not the address of any object then how could it be possible to copy anything to it? 如果str不是任何对象的地址,那么如何将任何内容复制到它?

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

}

Its always important to indent your code also :$ 缩进代码也总是很重要的:$

您可以使用malloc或strdup。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM