I am trying to figure out why I can't store characters into my char pointer by using the strcpy() command. I get a seg fault when I run the code below.
#include <stdio.h>
#include <string.h>
int main(int argc, const char *argv[])
{
char *str1, *str2;
int ret;
strcpy(str1, "abcdefg"); // stores string into character array str1
strcpy(str2, "abcdefg");
printf("contents of %s \n", str1);
ret = strncmp(str1, str2, strlen(str2)); /* compares str1 to str2 */
if (ret > 0) {
printf("str1 is less than str2\n");
}
else if (ret < 0) {
printf("str2 is less than str1\n");
}
else if (ret == 0) {
printf("str1 is equal to str2\n");
}
return 0;
}
Thank you!
Right now, str1
and str2
are just pointers to a character.
When you do strcpy(str1, "abcdefg")
, it attempts to write the characters in the string "abcdefg" into the memory that str1
points to and since str1
points to an unknown memory, which probably you don't have any write permissions, you get a segmentation fault.
One way to fix it is to allocate memory on the heap and then store these strings.
#include <stdlib.h>
...
/* assuming the max length of a string is not more than 253 characters */
char *str1 = malloc(sizeof(char) * 254);
char *str2 = malloc(sizeof(char) * 254);
You can also use strdup
to duplicate the string like Gangadhar has mentioned.
Another way is to declare str1
and str2
as arrays during the compiling as Bryan Ash suggested
char str1[] = "abcdefg";
char str2[] = "abcdefg";
In case, you want to allocate the string dynamically but not on the heap, you can use alloca
(for more details read http://man7.org/linux/man-pages/man3/alloca.3.html) as kfsone noted
compiling this with the -Wall
command gives a useful hint
test.c:12:10: warning: 'str1' is used uninitialized in this function [-Wuninitialized]
printf("contents of %s \n", str1);
^
test.c:14:17: warning: 'str2' is used uninitialized in this function [-Wuninitialized]
ret = strncmp(str1, str2, strlen(str2)); /* compares str1 to str2 */
Given this example, you don't even need strcpy, you could use:
char str1[] = "abcdefg";
char str2[] = "abcdefg";
If you want to learn more about pointers, there's an excellent free e-book titled Pointers and Memory from Stanford CS Education Library.
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