This program illustrates my question:
#include "stdio.h"
#include "string.h"
void first_try() // segmentation fault
{
size_t numc = 1;
char *dest = "i "; // this is bad? i need to declare character array first? why?
char *src = "lone wolf c program\n";
memcpy(dest, src, numc);
printf("%s", dest);
}
void second_try() // works
{
size_t numc = 1;
char dest[24] = "i get overwritten";
char *src = "lone wolf c program\n";
memcpy(dest, src, 20);
printf("%s", dest);
}
int main(void)
{
//first_try(); // run-time error
second_try();
}
Why does the first_try()
method cause a segmentation fault error?
Context
// feel free to ignore this context
I'm still a c programming newb. I went to https://www.devdocs.io and looked at the api for memcpy()
.
My instinct was to immediately write first_try()
. I don't understand the difference between the dest
variables in each function. Don't they both contain valid address values?
I read in a "strings as pointers" blog that "the character array containing the string must already exist". Apparently, writing just char *dest = "string";
compiles but is less useful than writing char buf[] = "string";
with a follow-up ptr that can be passed around: char *dest = &buf;
. I'd like to understand the 'why' in all of this.