Why heap corruption happened?

113 Views Asked by At

I have an Unroll Linked List

class UnrolledLinkedList {
    Node* head;
    Node* tail;
    int size; //num of elements in List
    int numOfNodes;
    int nodeSize;
}

with Node like this

class Node {
private:
    int maxElements;
public:
    int numElements; // number of elements in this node, up to maxElements
    int* elements; // an array of numElements elements,
    Node *next; // reference to the next node in the list
    Node *prev; // reference to the previous node in the list
}

And I want to put elements in an array. This is my funtion:

int* UnrolledLinkedList::toArray() {
int* arr = new int(size);
Node* pTemp = head;
int i = 0, j = 0, temp = 0;
while (pTemp) {
    i = 0;
    while (i < pTemp->numElements) {
        if (i != 0) j++;
        *(arr + j) = pTemp->elements[i];
        i++;
    }
    pTemp = pTemp->next;
    j++;
}
return arr;
}

And When I called this

int* arr = list->toArray();
int n = list->getSize();
printf("The list after converted to array:\n");
            if (n > 0) {
                for (int i = 0; i < n; i++)
                    printf("%d ", arr[i]);
                printf("\n");
                delete[] arr;
            }
            else {
                printf("NULL\n");
            }

in main, it caught an error HEAP CORRUPTION DETECTED at line delete[] arr; Please help me! Thank you in advance!

1

There are 1 best solutions below

0
On

The following statement doesn't work as you think:

    int* arr = new int(size);

It creates a single int, intialized with the value size.

Your code will certainly work better with:

    int* arr = new int[size];