Home > Blockchain >  realloc() deletes first element
realloc() deletes first element

Time:11-08

I have this function:

node* creaNodo(coordinata pos, node** known, int* nKnown){
    node* nodo = exists(known, pos, *nKnown);
    if(nodo == NULL){
        (*nKnown)  ;
        realloc(known, (*nKnown) * sizeof(node*));
        nodo = malloc(sizeof(node) * 1);
        nodo->nNextNodes = 0;
        nodo->nextNodes = NULL;
        nodo->nPreviousNodes = 0;
        nodo->previousNodes = NULL;
        nodo->posizione = pos;
        known[*nKnown - 1] = nodo;
    } 
    return nodo;
}

It basically check if a node already exists in my array (known) and if it doesn't it add it to my array or, if it does, it return the existing node. I'm having this weird behavior with realloc where after some iteration of me calling the function the realloc lose the first element of my array setting its value to NULL (0x0). I checked this by running the code with gdb and adding to my watchlist known[0]. I tested it using this main:

int main(){
    node** known = malloc(sizeof(node*) * 1);
    int nKnown = 0;
    for(int i = 0; i < 20; i  ){
        coordinata* tmp = assegnaCoordinata(i,i);
        creaNodo(*tmp, known, &nKnown);
    }
}

CodePudding user response:

The return value of the call of realloc is not stored in any variable

realloc(known, (*nKnown) * sizeof(node*));

so such a call invokes undefined behavior if you will try to access the memory by the address stored in the variable known.

At least you need to write

known = realloc(known, (*nKnown) * sizeof(node*));

though it is better to use an intermediate variable because the function can return a null pointer as for example

node** tmp = realloc(known, (*nKnown) * sizeof(node*));

if ( tmp != NULL ) known = tmp;
//... 
  • Related