0

I have defined struct Node and createNode function.

typedef struct {
    int r, c;
    int val;
    struct Node* down, *right;
} Node;

typedef Node* NodePointer;    

NodePointer createNode(int r,int c,int val) {
        NodePointer p = (NodePointer)malloc(sizeof(NodePointer));
        if (p != NULL) {
            p->r = r;
            p->c = c;
            p->val = val;
            p->down = p->right = NULL;
        }
        return p;
}

Then when I tried to use it in main function

int i = 0;
NodePointer* rows = (NodePointer*)malloc(50*sizeof(NodePointer));
for (i = 0; i < 20; i++) {        
    rows[i] = createNode(i,i+10,i*i);
}

It threw runtime error, but when I changed for loop like this(change is in for loop - executes only once):

for (i = 0; i < 1; i++) {        
    rows[i] = createNode(i,i+10,i*i);
}

It didn't throw error. So I ask what am I doing wrong; Error:

Zad1: malloc.c:2374: 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.
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Kid1234
  • 29
  • 4

1 Answers1

5

Change this:

NodePointer p = (NodePointer)malloc(sizeof(NodePointer));

to this:

Node p = malloc(sizeof(Node));

since you want to allocate elements of type Node, not NodePointer.

Tip: Casting the return of malloc() didn't cause the error, but you shouldn't do it, as discussed in Do I cast the result of malloc?

PS: Didn't if felt weird when you allocated the same type for both p and rows? ;)

gsamaras
  • 71,951
  • 46
  • 188
  • 305