user3452283
user3452283

Reputation: 1

Regarding pointers and malloc errors

I am writing code for a compiler for a toy language. This is a snippet of the code. In main there are two functions: createlist and node. When one is commented out, the other one works fine, but together it shows an error which I don't understand. Any help is appreciated.

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

struct node {          //declaration for node
    int tokenno;
    struct node * next ;
};

struct node * newnode(int a)          // to create a new node
{
    struct node * new1  = (struct node *)malloc(sizeof(struct node));
    printf("\n malloc sucees");

    (*new1).tokenno = a ;
    (*new1).next = NULL ;
    printf("\new node sucess\n");
    return (new1);
};

struct firstlist{
    int size ;
    struct node * list[10];
};

typedef struct firstlist * plist; 

plist createlist(){                 //fun to create a first list
    int i ;                              

    plist p  = (plist) malloc(sizeof(struct firstlist));
    (*p).size = 10 ;
    for(i = 0 ; i <=10;i++){           //initializing list[i] to NULL
        (*p).list[i] = NULL ;
    }
    printf("\n created sucessfully");
    return p;
}

int main(){                         
    plist p ;
    //p = createlist(); // If you comment createlist the new node works fine
    //getfirstset(p);
    //insert(1,5,p);          
    newnode(2);
}

If you comment out newnode then createlist works fine, but together it shows the following error:

a.out: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) 
&& old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1))
& ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
created sucessfullyAborted

Upvotes: 0

Views: 414

Answers (1)

jpw
jpw

Reputation: 44881

The reason it crashes is that you write outside the bounds of the array in the createlist function:

for(i = 0 ; i <= 10; i++)

should be:

for(i = 0 ; i < 10; i++)

When you comment out the newnode function it's still not working correctly, but the reason it won't crash is that there are no more memory accesses that will trigger the memory error.

There might be other issues, but change this and the program will run.

On a side note, the nodes you create are never put into the list, but maybe you've just not written that part of the code yet (I guess it would be the insert function).

Also, instead of (*p).size you can write p->size which to many people are more readable.

Lastly: as you declared main to return an int you should end the program with a return 0; statement.

Upvotes: 3

Related Questions