Question

I have a small doubly-linked list application. I want to add elements inside the list and then display the list normally. At the output i get my inserted elements allright, but after them i get a bunch of strange numbers( such as .... 28482 -20048 2817 ...... ) I believe it's a problem of space allocation.

Any help is appreciated, thanks in advance!

# include <stdio.h>
# include <conio.h>
# include <string.h>
# include <stdlib.h>

typedef struct elem { 
    int number; 
    struct elem * urm;
    struct elem * prec;
}nod; 



nod *prim=NULL,*ultim=NULL, *local=NULL, *p=NULL;

void insert_element(int numb){

    nod *local=(nod *)malloc(sizeof(nod));
    local->number = numb;

    if (prim==NULL){
        prim=local;
        ultim=local;
    }
    else{
        ultim->urm = local;
        local->prec = ultim;
        ultim=local;
    }
}

void load_data()
{
    int i,n;
    nod *c = (nod *)malloc(sizeof(nod));
    printf("\n cate elemente va avea lista?");
    scanf("%d", &n);
    printf("avem %d elemente", n);
    for(i=1;i<=n;i++){
    printf("\n number: ");
    scanf("%d", &c->number);
    insert_element(c->number);
    }
}

void list_left_to_right()
{
    nod *p = (nod*) malloc(sizeof(nod));
    p=prim;

    while(p){
    printf("%d ", p->number);
    p=p->urm;
    }
    printf("\n");
}

int main()
{
    int op;

    do{
    printf("\n1.Enter some data\n");
    printf("2.Display left - > right the data\n");
    printf("0.Exit\n");
    printf("choice : ");
    scanf("%d",&op);

    switch(op){
    case 1: load_data(); break;
    case 2: list_left_to_right(); break;
    case 0: break;}
    }
    while (op!=0);
    return 0;
}
Was it helpful?

Solution

(1) You have a memory leak in list_left_to_right():

nod *p = (nod*) malloc(sizeof(nod));
p=prim;

This leaks the block returned by malloc().

(2)

void insert_element(int numb) {
    nod *local=(nod *)malloc(sizeof(nod));
    local->number = numb;
    // TODO: set local->urm and local->prec to NULL

    if (prim==NULL) {
        prim=local;
        ultim=local;

OK, so the first time insert_element() is called, the new element is both the head and the tail.

Bug: You need to set the urm and prec fields to NULL. They have undefined values initially.

    }
    else {
        ultim->urm = local;      
        local->prec = ultim;
        ultim=local;
    }
}

After that, the subsequent elements are inserted as a new tail (ultim).

Bug: But again you need to make sure that local->urm is set to NULL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top