The following code always segfaults:
char *test3 = (char *) malloc(sizeof(char) * 5);
test3 = "asdf";
printf("%s\n", test3);
The following code does not segfault:
char *test3 = (char *) malloc(sizeof(char) * 5);
test3[0] = 'a';
test3[1] = 'b';
test3[2] = 'c';
test3[3] = 'd';
test3[4] = '\0';
printf("%s\n", test3);
I guess the question may be how do I assign a cstring literal to dynamically created cstring?
The correct way to "fill" a string is:
strcpy(test3, "abcd");
However, I would strongly recommend that you don't use malloc [and DEFINITELY don't use (char *) malloc(...) - since that can hide some rather nasty bugs that jump up and bite you at least opportune moment, as bugs do have a tendency to do that - you are probably doing that because you are compiling your C-code as C++-code, which is wrong, and teaches you bad habits like this one].
Using malloc to allocate small strings is a large waste of space. Your 5 character string probably has an overhead of 16-32 bytes, and will be rounded to 8 or 16 bytes. So in total it could be using 48 bytes, to store 5 bytes - that's a BIG waste of space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With