Reputation: 2069
Consider following C code -
typedef struct node
{
int data;
}node;
int main()
{
node *temp;
temp->data=100;
printf("%d",temp->data);
return 0;
}
It gives Segmentation fault
on line containing temp->data=100;
because (I think) I haven't allocate memory for it. So, there is nothing such as temp->data
.
But, when I try with -
int main()
{
node *temp,*n;
n=(node*)malloc(sizeof(node));
n->data=100;
temp->data=n->data;
printf("%d",temp->data);
retrun 0;
}
It gives proper output 100.
I haven't allocate memory where temp
will point. But still I am copying n->data
to temp->data
. How ??
Upvotes: 1
Views: 346
Reputation: 390
Your first code is also right just "temp" is pointing to a garbage value so you have to initialized that.
temp=(node *)malloc(sizeof(node));
Upvotes: 1
Reputation: 13580
That you haven't got a segfault in temp->data=n->data;
is just coincidence. temp
is not initialized and hence it points into the digital nirvana.
When you've called malloc
you've allocated sizeof node
bytes (in reality it may be even a little more) and then you have full memory access to the block pointed to by n
.
In general you should call malloc
in this way:
node *n;
n = malloc(sizeof *n);
sizeof *n
instead of sizeof <datatype>
. If you change the datatype (for example you have a typo and instead of typedef .... node
you've writen typedef ... nhode
. Then you only have to change the declarations of the variables and the rest of the code doesn't have to be changed at all.Upvotes: 1
Reputation: 138
The temp pointer takes some garbage value as its not initialised. By chance temp has a garbage value which may happen to be legal address for your program so it runs. If garbage value has illegal adress it will generate segment fault.
Upvotes: 2
Reputation: 48300
You're lucky.
Local variables are not initialized automatically, so when the program begins, both temp
and n
contain whatever values happen to be on the stack. Next, memory is allocated and n
is set to point to it. The value 100 is stored in the data
member of the structure.
But temp
is still uninitialized, so the value 100 is copied into an unspecified area of memory. Depending on where that memory happens to be, the program may segfault, or it may simply corrupt memory that it doesn't own.
Upvotes: 1
Reputation: 2366
Your right on the first part, it segfaults because node* temp isn't pointing anywhere (well, somewhere, but not to allocated memory).
I don't know why the second one "works". I suspect it only appears to work, in that it's not crashing. But since temp was never initialized, who know where it's sticking that '100'. Maybe just hanging around to crash later. Either way, writing to unitialized memory isn't a good idea ;-0
Upvotes: 0