Re: C programming: Segmentation fault within malloc?
* Shaul Karl (shaulka@bezeqint.net) spake thusly:
...
> 193 enum flag insert_symbol(struct symbol *sym)
> 194 {
> 195 struct node *node;
> 196
> 197 if (!((node = (struct node *)malloc(sizeof(struct node))) &&
> 198 (node->data = (struct symbol *)malloc(sizeof(struct
> symbol))))) {
> 199 fprintf(stderr, sym_tab_msg[MEMORY_ALLOCATION_FAILURE]);
> 200 return FALSE;
> 201 }
> (gdb) n
>
> Program received signal SIGSEGV, Segmentation fault.
> 0x400af19e in malloc () from /lib/libc.so.6
> (gdb)
You know, I tend to write simple stupid code these days. When the above
is written like
node = (struct node *)malloc(...);
if( node == NULL ) return( E_MALLOC );
tmp = (struct symbol *)malloc(...);
if( tmp == NULL ) return( E_MALLOC );
node->data = tmp;
it's easier to debug. Presumably the compiler will optimize this form and
your form to about the same sequence of instructions, so you don't gain
much by stringing it into single if statement. OTGH with simple stupid code
you can see which malloc() segfaults.
> How can it be? If malloc can not allocate memory it should return a NULL
> pointer. How can it Seg fault?
Well, I've seen gcc overwrite previously allocated memory and _not_ segfault,
so I wouldn't get too excited here.
Dima
--
E-mail dmaziuk at bmrb dot wisc dot edu (@work) or at crosswinds dot net (@home)
http://www.bmrb.wisc.edu/descript/gpgkey.dmaziuk.ascii -- GnuPG 1.0.4 public key
One distinguishing characteristic of BOFHen is attention deficit disorder.
Put me in front of something boring and I can find a near-infinite number
of really creative ways to bugger off. -- Antony De Boer in asr
Reply to: