Gideon
Gideon

Reputation: 37

Segmentation fault when calling strcpy

I was trying to use strncpy and then strcpy and vice versa, but I kept receiving a segmentation fault during runtime. I thought this was because of an logical error in the functions, but I switched their places and only the first one would execute.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char c = ' ', sentence[50], *pointer_to_string;
    pointer_to_string = &sentence[0];
    int index = 0;

    printf("Please enter a sentence:");
    while ((c = getchar()) != '\n')
    {
        sentence[index] = c;
        index++;
    }
    sentence[index] = '\0';

    char *string_copy1, *string_copy2;

    strncpy(string_copy1, pointer_to_string, 5);
    printf("strncpy(string_copy1, pointer_to_string, 5):\n");
    printf("%s\n", string_copy1);

    strcpy(string_copy2, pointer_to_string);
    printf("strcpy(string_copy2, pointer_to_string):\n");
    printf("%s\n", string_copy2);
}

Upvotes: 0

Views: 3976

Answers (1)

boriaz50
boriaz50

Reputation: 856

See documentation:

char *strcpy(char *dest, const char *src);

The first argument is a pointer to the destination buffer. But your pointers are not initialized:

char *string_copy1, *string_copy2;

Therefore, pointers contain some garbage values. And strcpy() writes to the memory that does not belong to your program. It causes segmentation fault.

Do

char string_copy1[50] = { 0 };
char string_copy2[50] = { 0 };

Filling them with zeros is neccessary to avoid problems with strncpy():

If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

Upvotes: 3

Related Questions