Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault with strcpy [duplicate]

I am wondering why am I getting segmentation fault in the below code.

int main(void)
{
        char str[100]="My name is Vutukuri";
        char *str_old,*str_new;

        str_old=str;
        strcpy(str_new,str_old);

        puts(str_new);

        return 0;
}
like image 359
Teja Avatar asked Apr 26 '12 02:04

Teja


2 Answers

You haven't initialized *str_new so it is just copying str_old to some random address. You need to do either this:

char str_new[100];

or

char * str = (char *) malloc(100);

You will have to #include <stdlib.h> if you haven't already when using the malloc function.

like image 63
seanwatson Avatar answered Sep 24 '22 01:09

seanwatson


str_new is an uninitialized pointer, so you are trying to write to a (quasi)random address.

like image 33
geekosaur Avatar answered Sep 24 '22 01:09

geekosaur