ryuzakinho
ryuzakinho

Reputation: 1919

passing pointer to function and using realloc

I want to pass a pointer to a function which will call a second function that will use realloc. The issue is that realloc is returning NULL.

I don't know if the mistake is in the numbers of * in the function call or something else.

Could you please help me ?

The code:

int main(){

// some code.
clause_t* ptr; //clause_t is a structure i declared.

//Some work including the initial allocation of ptr (which is working).

assignLonely(matSAT, ic.nbClause, ic.nbVar, ptr); //the issue is here.

//Some other work
}

void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t* ptr)
 {

   int i = 0, j = 0;
   int cpt = 0;
   int indice = -1; 

for (i = 0; i < nbClause ; ++i)
{
    j = 0;
    cpt = 0;
    while((j < nbVar) && (cpt < 2))
    {
        if (matSAT[i][j] != 0)
        {
            cpt++;
        }
        else
        {
            indice = j;
        }

        if (cpt < 2)
        {
            deleteClause(indice, &ptr);
        }

        j++;
    }
}
}

void deleteClause(int indiceClause, clause_t** ptr)
{
    int i = indiceClause;
    int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);
    int tailleElt = sizeof((*ptr)[0]);

while(i+1 < nbElt)
{
    (*ptr)[i] = (*ptr)[i+1];
    i++;
}

*ptr = (clause_t*)realloc(*ptr, (nbElt-1)*tailleElt);
if (*ptr == NULL)
{
    fprintf(stderr, "Erreur reallocation\n");
    exit(EXIT_FAILURE);
}

}

Upvotes: 1

Views: 879

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

You have to declarae function assignLonely similarly to function deleteClause like

void assignLonely(int** matSAT, int nbClause, int nbVar, clause_t** ptr);

if you want that changes of ptr in the function would be stored in the original object in main.

Also take into account that this statement

int nbElt = sizeof((*ptr))/sizeof((*ptr)[0]);

is wrong. Expression sizeof((*ptr)) will return the size of the pointer. Pointers do not keep information about how many elements in arrays they point to.

So expression

(nbElt-1)

can be equal to zero or even be negative.

Upvotes: 2

Related Questions