Segmentation Fault when using strupr(...) with GCC compiler
When run following code after compiling on gcc,I get segmentation fault.
#i开发者_运维知识库nclude <stdio.h>
#include <string.h>
int main(void)
{
struct emp
{
char *n;
int age;
};
struct emp e1={"David",23};
struct emp e2=e1;
strupr(e2.n);
printf("%s\n%s\n",e1.n,e2.n);
return(0);
}
String literals like "David"
cannot be altered, which is what you're doing when you call strupr
. You should copy the string (e.g. with strdup
) before.
You are getting a seg fault because
struct emp e1={"David",23};
"David" resides in data, so it is a read-only, or const, string.
When you
strupr(e2.n);
You are trying to modify that same const string.
Working code:
struct emp e2;
e2.age = e1.age;
e2.n = (char *)malloc(SOME_SIZE);
strcpy(e2.n, e1.n); //here you copy the contents of the read-only string to newly allocated memory
strupr(e2.n);
printf(...);
free(e2.n);
return 0;
By doing struct emp e1={"David",23};
you have made "David" a string literal, which is read-only in nature. In the executable it is stored in the .rodata
or equivalent section of the executable, which is read-only. by the strupr ()
you are attempting to modify this read-only data, and thus a segmentation fault.
精彩评论