Search code examples
csegmentation-faultstrncpy

strncpy seg fault, but am able to assign string manually


I have a global pointer to char arrays defined (on the stack I believe?) as:

char *history[BUFFER_SIZE];

And inside a method I simply want to:

strncpy(history[0], str, length);

and it seg faults. It doesn't make sense to me since:

history[0] = "a string"

doesn't seg fault.

My questions:

  1. Since I am defining the array of char arrays like this, I shouldn't have to do any sort of malloc or initialization, correct?
  2. Why is it seg faulting?

Solution

  • char *history[BUFFER_SIZE]; is an array of char*s that point to nowhere. When you try to strncpy to those pointers, you invoke undefined behavior (because they point to nowhere), and you're seeing this manifested as a segfault.

    When you history[0] = "a string" this assigns the char* at history[0], so history[0] no longer pointer to nowhere, it points to "a string". "a string" is a string literal, stored elsewhere in your program, most likely the read-only section. history[0] does not actually contain the data "a string", it simply contains the address of where "a string" resides.

    Since I am defining the array of char arrays like this, I shouldn't have to do any sort of malloc or initialization, correct?

    That depends on what you want to do. It's perfectly fine to do history[0] = "a string", just know that trying to modify that string is also undefined behavior, since it is a string literal. If you want to copy the string literal to a section of memory where you can freely modify the copy, you will have to allocate some memory with malloc or similar. But char *history[BUFFER_SIZE]; isn't defining an "array of char arrays", it's defining an array of char pointers.