Trying to copy a char *str
to char c[]
but getting segmentation fault or invalid initializer error.
Why is this code is giving me a seg fault?
char *token = "some random string";
char c[80];
strcpy( c, token);
strncpy(c, token, sizeof c - 1);
c[79] = '\0';
char *broken = strtok(c, "#");
char* is a pointer to a character, which can be the beginning of a C-string. char* and char[] are used for C-string and a string object is used for C++ springs. char[] is an array of characters that can be used to store a C-string.
The fundamental difference is that in one char* you are assigning it to a pointer, which is a variable. In char[] you are assigning it to an array which is not a variable.
This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings. C-strings of this form are called “string literals“: const char * str = "This is a string literal.
char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").
use strncpy()
rather than strcpy()
/* code not tested */
#include <string.h>
int main(void) {
char *src = "gkjsdh fkdshfkjsdhfksdjghf ewi7tr weigrfdhf gsdjfsd jfgsdjf gsdjfgwe";
char dst[10]; /* not enough for all of src */
strcpy(dst, src); /* BANG!!! */
strncpy(dst, src, sizeof dst - 1); /* OK ... but `dst` needs to be NUL terminated */
dst[9] = '\0';
return 0;
}
use strncpy to be sure to not copy more charachters than the char[] can contains
char *s = "abcdef";
char c[6];
strncpy(c, s, sizeof(c)-1);
// strncpy is not adding a \0 at the end of the string after copying it so you need to add it by yourself
c[sizeof(c)-1] = '\0';
Edit: Code added to question
Viewing your code the segmentation fault could be by the line
strcpy(c, token)
The problem is if token length is bigger than c length then memory is filled out of the c var and that cause troubles.
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