Re: Does structure order matter?



Brian Dude wrote:

> Hello, I've been quite comfortable using linked list for a
> while now without much hassle, but lately I've been getting
> problems from unexpected places. I'm working on a graphing
> utility program, and to allow multiple functions to be entered
> I figured the best way would be with a linked list:
>
> struct List{
> int color; /*The color it will be when drawn*/
> int index; /*It's index: Y1, Y2, etc...*/
> char Y[76]; /*The function itself*/
> struct List *prev;
> struct List *next;
> }*current,*first,*hold,*last;
>
> And I use a switch to process user input...
> (Last is the last node before NULL and hold is a general
> placeholder)
>
> switch(r){
> case INSERT: /*When the Insert key is pressed*/
> /*Do some graphics related stuff*/
> /*Add a node to the end of the list*/
> last->next=malloc(sizeof(struct List));
> if(last->next==NULL){
> puts("Cannot allocate function memory.");
> exit(1);
> }
> hold=last;
> last=last->next;
> last->prev=hold;
> last->next=NULL;
> last->color=hold->color+1;
> last->index=hold->index+1;
> /*More graphics stuff*/
> ggets(last->Y,76); /*<-My own string input function*/
> /*More graphics stuff*/
> break;
>
> From the above, I get errors. Running through the list is fine
> from first to last but from last to first it points to
> garbage. But I noticed everything seems to run fine if I put
> the:
>
> last->prev=hold;
> last->next=NULL;
>
> after the ggets() statement. It's really confusing me as to
> why. Or is this a different problem entirely that I may have
> overlooked? I greatly appreciate any input.
>
> Brian Dude

Can it be that your ggets() overruns Y buffer, thus corrupting
prev and next fields? The fact that it works fine if you repeat
their initialisation after calling ggets() suggests exactly
this.

Cheers

Vladimir
.