• C

Easy Function question

I have created a self referential structure and am creating a stack to do tree searches, when I push onto the stack everything is fine, but when I pop the first element off the stack and free the memory for the popped item the previous node is also "freed". So the first iteration of my for loop to print out the stack recieves 'f', but then doesn't seem to be pointing to the previous node (or the previous node has been corrupted... Here is the code:


struct DL_Node{
      char element;
      struct DL_Node *prev;
      struct DL_Node *next;
};

struct DL_Node *push(struct DL_Node *n, int a){
      struct DL_Node *p;

      if (!n->element)
            n->element = a;
      else{
            p = malloc(sizeof(struct DL_Node));
            p->element = a;
            p->prev = n;
            p->next = NULL;
            n->next = p;
            n = p;
      }
      return n;
}

char pop(struct DL_Node *n){
      char a;

      a = n->element;
      if (n->prev){
                      n = n->prev;
            free(n->next);
            n->next = NULL;
      }
      else
            free(n);

      return a;

}

void main(){
      struct DL_Node *s;
      struct DL_Node *root;
      int i;
      root = malloc(sizeof(struct DL_Node));
      root->element = (char) NULL;
      root->next = NULL;
      root->prev = NULL;

      s = push(root, 'c');
      s = push(s, 'd');
      s = push(s, 'e');
      s = push(s, 'f');

      while (s->prev)
            printf("%c\n", pop(s));

}
raistlinx17Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tzxie2000Commented:
the problem is because
when you call
char pop(struct DL_Node *n)

you assigned  n = n->prev; and expect n to point to the next value

but the value n is called by point value so it is not change
0
tzxie2000Commented:
you could change code as

struct DL_Node{
     char element;
     struct DL_Node *prev;
     struct DL_Node *next;
};

struct DL_Node *push(struct DL_Node *n, int a){
     struct DL_Node *p;

     if (!n->element)
          n->element = a;
     else{
          p = malloc(sizeof(struct DL_Node));
          p->element = a;
          p->prev = n;
          p->next = NULL;
          n->next = p;
          n = p;
     }
     return n;
}

char pop(struct DL_Node **p){//<-------------change to the reference
     char a;

       struct DL_Node *n;
     n=*p;
 
     a = n->element;
     if (n->prev){
                     n = n->prev;
          free(n->next);
          n->next = NULL;
     }
     else
     {
          free(n);
         n=NULL;
    }
    *p=n;
     return a;

}

void main(){
     struct DL_Node *s;
     struct DL_Node *root;
     int i;
     root = malloc(sizeof(struct DL_Node));
     root->element = (char) NULL;
     root->next = NULL;
     root->prev = NULL;

     s = push(root, 'c');
     s = push(s, 'd');
     s = push(s, 'e');
     s = push(s, 'f');

     while (s)
          printf("%c\n", pop(&s));

}
0
raistlinx17Author Commented:
But isn't *n just a pointer? Can't I set is to whatever position (memory location) in the list I want and the calling code will have this new value? i.e Am I not passing by reference?
0
Managing Security Policy in a Changing Environment

The enterprise network environment is evolving rapidly as companies extend their physical data centers to embrace cloud computing and software-defined networking. This new reality means that the challenge of managing the security policy is much more dynamic and complex.

aib_42Commented:
First things first:

1) main() returns int. Functions that take no parameters should be declared as taking 'void':
> void main(){
should be:
int main(void)

2) Always check the return value of malloc. It will be NULL if there is a problem with the memory allocation.

3) Casts.
> n->element = a;
will demote the int a to a char, but it should be no problem.
> root->element = (char) NULL;
NULL is used for pointer-context and its definition is compiler-dependent. The integer '0' will be converted to the null-pointer equivalent when used in a pointer-context, but the reverse is not true for the macro 'NULL'. Use 0 or '\0' instead. If you really want the three lines to look similar, use:
root->element = 0;
root->next = 0;
root->prev = 0;
Where the last two 0's will automatically be converted to the null pointer value used on your platform.

...and now to the problem:

pop() is freeing the structure alright, but you keep referring to the freed thing. Let's open up the while(){pop()} loop:
>while (s->prev)
>     printf("%c\n", pop(s));
Explode this to:

if (s->prev)
    printf("%c\n", pop(s));
if (s->prev)
    printf("%c\n", pop(s));
if (s->prev)
    printf("%c\n", pop(s));
if (s->prev)
    printf("%c\n", pop(s));
if (s->prev)
    printf("%c\n", pop(s));
.....

The first 'if' expression is returning true, and your first printf+pop pair is being executed. The pop() is freeing what s points to, and after that, you're referring to 'freed' memory, causing an undefined behvaiour. You should modify pop() so that it updates your pointer to point to the previous struct, now at the end of the stack. See these examples:

while(s->prev) s = pop(s, &some_char); /* pop returns the new top of the stack in its return value, and the 'element' of the previous top in some_char */

while(s->prev) printf("%c\n", pop(&s)); /* pop returns the element as usual, but takes a pointer to a pointer to struct DL_Node as a parameter. It first _reads_ s to free it, and then _writes_ to s the address of the new top struct */

or if you don't want to modify pop():

struct DL_Node *temp;

while(s->prev) {
    temp = s->prev;
    printf("%c\n", pop(s));
    s = temp;
}    
0
tzxie2000Commented:
for example
main()
{
 int *n;
 int a=1;
 n=&a;
 f(n);
 printf("%d",a);
}
 f(int * a)
 {
    a=2;
 }

you will get 2 as result

and when you call

 int a=1;
 int b=2;
main()
{
 int *n;
 n=&a;
 f(n);
 printf("%d",n==&b);
 printf("%d",n==&a);
}
 f(int * n)
 {
    n=&b;
 }
 
 you will get
 0//false
 1//true
 
 as you want to change the data store in n but not the data n point to
the data store in n is not changed
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
aib_42Commented:
...what tzxie2000 wrote would be my second example. There were no other replies when I started writing mine, sorry :).
0
aib_42Commented:
...what tzxie2000 wrote _the_first_time_ would be my second example. His other reply wasn't here when I started writing my last reply, sorry :).
0
tzxie2000Commented:
and suggest a few code link stack below

struct DL_Node{
     char element;
     struct DL_Node *next;
};

struct DL_Node *push(struct DL_Node *top, int a){
    struct DL_Node *p;

    p = malloc(sizeof(struct DL_Node));
    p->next=top;
    p->element = a;
    return top;
}

char pop(struct DL_Node **top)
{
                  struct DL_Node *n;
                  char a;
                  
             if(!(*top)->next) return (char)(NULL);
             a=(*top)->element;
             n=(*top)->next;
     free(*top);
     *top=n;
     return a;
}

int isempty(struct DL_Node *top)
{
      return top->next;
}

void main(){
     struct DL_Node *top;
     int i;
     top = malloc(sizeof(struct DL_Node));
     top->element = (char) NULL;
     top->next = NULL;

     top = push(top, 'c');
     top = push(top, 'd');
     top = push(top, 'e');
     top = push(top, 'f');

     while (!isempty(top))
          printf("%c\n", pop(top));
}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.