Reputation: 1466
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;
}
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
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
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