Reputation: 45
I wrote this code because I'm having a similar problem in a larger program I'm writing. For all I know the problem is the same so I made this small example.
#include <stdio.h>
typedef struct
{
int x;
char * val;
}my_struct;
int main()
{
my_struct me = {4, " "};
puts("Initialization works.");
me.val[0] = 'a';
puts("Assignment works.");
puts(me.val);
puts("Output works.");
return 0;
}
When compiled with tcc (Tiny C Compiler) it compiles and executes fine. But using GCC 4.6.0 20110513 (prerelease) it compiles, however, when I execute it I only get past "Initialization works." before getting a segfault.
What am I doing wrong? Is it my code or my GCC compiler?
Upvotes: 0
Views: 1348
Reputation: 6919
As other answers have pointed out, val
is pointing at a string constant. Try
my_struct me = {4, malloc(2)};
and remember to check if val
is NULL
if you're using this in a real program.
Upvotes: 0
Reputation: 34655
val
is an points to read only location.
char *readOnly = "Data in read only location" ;
readOnly
pointing data cannot be modified.
Upvotes: 0
Reputation: 61457
Your code. ANSI permits string constants to be read-only, and this is encouraged because it means they can be shared system-wide across all running instances of a program; gcc
does so unless you specify -fwritable-strings
, while tcc
makes them writable (probably because it's easier).
Upvotes: 8