0

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);
}
boriaz50
  • 860
  • 4
  • 17
Gideon
  • 37
  • 1
  • 9
  • 1
    Try to compile with `-g` flag and use valgrind while execute the program: `valgrind ./a.out` => you'll get more informations – YaatSuka Oct 05 '17 at 23:02
  • 2
    ` char *string_copy1, *string_copy2;` does not initialise either of those variables. So neither of them points at a valid memory location. Then you use str(n)cpy to overwrite the contents of an array of chars -- that is, a "string" -- but the pointer you give it does not point at such an array. So undefined behaviour ensues. – rici Oct 05 '17 at 23:08
  • 2
    You need to initialize `string_copy1` and `string_copy2;` before you use them. Using malloc find out how here http://en.cppreference.com/w/c/memory/malloc – Seek Addo Oct 05 '17 at 23:09
  • 2
    You can also use `malloc()` on `char *` to allocate memory for them and get ride of seg faults. `string_copy1 = malloc(50*sizeof(char));` `string_copy2 = malloc(50*sizeof(char));` and `pointer_to_string = malloc(50*sizeof(char)); ` – EsmaeelE Oct 05 '17 at 23:23

1 Answers1

3

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.

boriaz50
  • 860
  • 4
  • 17
  • How do I initialize them? And the first function with strncopy worked. – Gideon Oct 05 '17 at 23:05
  • Thank you, I pointed the pointers to new character arrays, and the functions worked. – Gideon Oct 05 '17 at 23:18
  • 2
    Don't use strncpy(). It doesn't do what you might expect, and it is in fact useless except for setting fixed-width fields in databases, which is the use for which it was designed. – Malcolm McLean Oct 05 '17 at 23:20
  • 1
    @MalcolmMcLean strncpy prevents overflowing the destination buffer. – Brandin Oct 05 '17 at 23:25
  • 4
    But it doesn't add a nul. So it is only useful if you have a non-nul terminated string of fixed width, which is never, except in certain database apps. – Malcolm McLean Oct 05 '17 at 23:27
  • 1
    The other problem with `strncpy()` is that if you have a big buffer and a short string to copy into it, every otherwise unused byte of the buffer is set to a null byte — it always writes to every position in the destination string, even though it doesn't guarantee to null terminate it either. It's a peculiar and hard to use function. If it is any consolation, `strncat()` is even harder to use right and therefore more deadly; don't use that, either. – Jonathan Leffler Oct 05 '17 at 23:37
  • 1
    @JonathanLeffler Simply put, `strncpy()` always writes `n` bytes. – boriaz50 Oct 06 '17 at 00:01