Anurag Rana
Anurag Rana

Reputation: 1466

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

Upvotes: 1

Views: 188

Answers (3)

haccks
haccks

Reputation: 106012

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?

Upvotes: 6

gkmohit
gkmohit

Reputation: 710

#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 :$

Upvotes: 2

unbesiegbar
unbesiegbar

Reputation: 461

You can use malloc or strdup in you case.

Upvotes: -1

Related Questions