Search code examples
c++dynamiclinked-listheap-memoryaccess-violation

Critical error detected while allocating from heap


In my program, I need to make a linked list but the size of the list (number of nodes) is defined during compile time. "newcustomer.numT" variable is the number of nodes that will be created. To do this I thought that I should have an array of pointers then I'd ask for memory from the heap by each pointer. BUT, unfortunately I also don't know the size of the array. I created it dynamically as well. "transactionn" is a struct which holds the values in a single node.

 transactionn **asd;
 asd = new transactionn*[newcustomer.numT];    //I created array of pointers
 for (int k = 0; k<newcustomer.numT; k++){
    asd[k] = new transactionn;  //Allocating a node for each pointer in the array
 } //End of the "node creating" 

 newcustomer.trahead = asd[0]; //Assign head to the first node

//Connecting nodes in the linked list to eachother
for (int z = 0; z < (newcustomer.numT)-1; z++){
    asd[z]->next = asd[z + 1];     
}
asd[newcustomer.numT]->next = NULL; //Set the next of the last node to NULL

When I compile it, there is no error on error list but in the output I get this:

Critical error detected c0000374
DataHomework2.exe has triggered a breakpoint.

And it triggers a break point in this line:

asd[k] = new transactionn;

What am I doing wrong?

Edit: I corrected the last index when so it is:

asd[(newcustomer.numT)-1]->next = NULL;

When I compile these codes as a one whole program, there is no error and program doesn't crash. When I implement this function to my main project program crashes again. Critical error.

Edit2 : These lines were correct. Source of the error was due to the values they get from other functions.


Solution

  • asd = new transactionn*[newcustomer.numT];    //I created array of pointers
    //...
    asd[newcustomer.numT]->next = NULL; //Set the next of the last node to NULL
    

    You overflow the array. The last index of array pointed by asd is newcustomer.numT - 1.