On Mar 2, 9:20 am, "seth...@gmail.com" <seth...@gmail.comwrote:
Hi everybody,
While i'm compiling the following program in GCC, it gives
"segmentation fault"
But GDB doesn't give any "segmentation fault"
What's the reason for this??
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main()
{
char name1[4];
int age1;
struct emp
{
char name[4];
int age;
};
struct emp *e1=malloc(sizeof(struct emp));
printf("enter name and age\n");
scanf("%s%d",name1,&age1);
printf("name1=%sage=%d\n",name1,age1);
e1->age=age1;
printf("\n%d",e1->age);
}
Thanks in advance,
Sethu
As pointed out the reason for the undefined behaviour
(sefault when run outside of GDB, works correctly
inside of GDB (undefined behaviour means anything
can happen, including what you expect))
is that you have allocated insufficient storage
for name1. But you also need to make sure that
whatever limit you put on the size of name1 you
do not try to put more characters in. In the
words of the Great Prophet Henry Spencer:
Thou shalt check the array bounds of all strings (indeed, all
arrays),
for surely where thou typest``foo'' someone someday shall type
``supercalifragilisticexpialidocious''
Why the difference between the behaviour inside and
outside GDB? Who knows? Possibly:
GDB put some extra space after data1,
space it might need to use at some
point (or maybe not). When you ran outside of GDB
there was no extra space, so your program tried
to write to memory it did not own, thus causing
your operating system to segfault ( a GOOD THING,
there are much worse things than a segfault.)
This type of behaviour is frequently seen. Often when
a program is compiled in debug mode everything is fine,
but compile in optimized mode (in general less forgiving
of buffer overruns) and the program segfaults.
Usually the senario is something like this: "Well after
one year, the 10 member team has finished the product.
We'll just switch to optimized mode for the shipping version
..... ARGGHHHH!!!!"
- William Hughes