简体   繁体   中英

Segmentation fault error (core dumped)

I am getting Segmentation fault (core dumped) error in below code.

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

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

You need to allocate memory for str before copying string to it.

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

Note that after assigning NULL to str , it points nowhere as c-faq says:

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

#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。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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