i'm trying to run a program using an array that i allocated manually with malloc(). I free() this array at the end of my program but i keep getting an error saying *** glibc detected *** ./test: double free or corruption (!prev): 0x0000000002177010 ***
Here is my main :
int main(int argc, char** argv)
{
pthread_t t1, t2, t3;
int i = 1;
int k = 0;
Client* clients;
clients = (Client*) malloc((nbClients+1)*sizeof(Client));
for (i = 1; i <= nbClients+1; i++)
{
printf("\n----TICKET%d----\n", i);
clients[i].panier = (int*) malloc(nbArticles*sizeof(int));
achats(clients[i].panier, &clients[i].ticket);
for (k = 0; k < nbArticles; k++)
{
printf("panier[%d] = %d\n", k, clients[i].panier[k]);
}
pthread_create(&t1, NULL, calcMACL, &clients[i]);
//calcMQUAD(clients[i].panier, &clients[i].ticket);
//calcMACL(clients[i].panier, &clients[i].ticket);
//calcMCUBE(clients[i].panier, &clients[i].ticket);
pthread_join(t1, NULL);
//free(clients[i].panier);
}
free (clients);
return 0;
}
Thanks for your help
You are accessing outside the bounds of the buffer you allocated, which possibly corrupts the malloc data structures resulting in the error you get. This is undefined behaviour.
The loop should be:
for (i = 0; i < nbClients+1; i++)
Remember, index starts from 0 in C.