Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 254
  • Last Modified:

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));

}
0
raistlinx17
Asked:
raistlinx17
  • 4
  • 3
1 Solution
 
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
Increase Security & Decrease Risk with NSPM Tools

Analyst firm, Enterprise Management Associates (EMA) reveals significant benefits to enterprises when using Network Security Policy Management (NSPM) solutions, while organizations without, experienced issues including non standard security policies and failed cloud migrations

 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get 10% Off Your First Squarespace Website

Ready to showcase your work, publish content or promote your business online? With Squarespace’s award-winning templates and 24/7 customer service, getting started is simple. Head to Squarespace.com and use offer code ‘EXPERTS’ to get 10% off your first purchase.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now