segmentation fault with strcpy [duplicate]
Asked Answered
G

3

23

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;
}
Grandeur answered 26/4, 2012 at 2:53 Comment(0)
S
41

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.

Sanctified answered 26/4, 2012 at 2:57 Comment(0)
H
9

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

Hort answered 26/4, 2012 at 2:55 Comment(0)
P
3

Because str_new doesn't point to valid memory -- it is uninitialized, contains garbage, and likely points into memory that's not even mapped if you're getting a segmentation error. You have to make str_new point to a valid block of memory large enough to hold the string of interest -- including the \0 byte at the end -- before calling strcpy().

Pancreatotomy answered 26/4, 2012 at 2:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.