So here i was, out of nowhere in particular writing a C program to do something. It would be compiled and run on a Linux Box.
My very first run gave me a Segmentation Fault. I have never encountered this before and my mind was now led into the labyrinth of segmentation concepts of processes that i had studied a couple of years back.
All i could comprehend was that i was doing something illegal with memory because of the pointers i was using. [THIS is why God made Java...]
A little googling revealed that my general thinking was right. But none of the snippets that i had read online were matching mine... One of the examples i read (on wikipedia) was this :
Exceute this,
My very first run gave me a Segmentation Fault. I have never encountered this before and my mind was now led into the labyrinth of segmentation concepts of processes that i had studied a couple of years back.
All i could comprehend was that i was doing something illegal with memory because of the pointers i was using. [THIS is why God made Java...]
A little googling revealed that my general thinking was right. But none of the snippets that i had read online were matching mine... One of the examples i read (on wikipedia) was this :
Exceute this,
const char* c = "hello";
*c = 'H';
and voila! You have your very own Segfault!
This is because, by writing const, you have, in essence, marked this particular memory chunk as READ ONLY. And when you try to write 'H' to the first byte referenced by it, you are violating that rule, hence the segfault.
What i was trying to do, was this:
int main (int argc, char** argv)
{
/*I tried different variations of the line below in my quest for a successfully running code, like char* followed by malloc.. and...only using char* */
char command[10];
strcpy(command, ""); //Did this too as one of my debugging steps
strcat(command,argv[1]); //THIS is where the segfault was occurring
}
So, to do away with it, i just tried this :char* src = argv[1];and then strcat(command,src);And this did away with the Segfault.I am not completely sure why, but i have a strong hunch (its been 3 years since i did some solid C ....because God made Java...) : It seems that the memory allocated to command line arguments is also marked READ ONLY. Essentially, by changing its contents you'd be violating that. Here, even though i'm not blatantly changing anything, i am after all concatenating which boils down to the fact that i am trying to join two memory chunks, one of which is READ ONLY, and the other is not.. hence the friction. But then again i'm a little confused because, by getting a different pointer to point to argv[1] its not like i'm changing the memory that the contents of argv[1] reside in... i'm just changing the pointer thats pointing to them..Well Segfault has fascinated me... and if i'm lucky enough i'll get some people commenting here who've had worse experiences with it :)Powered by ScribeFire.
0 comments:
Post a Comment