So I have a declare two structures like so
Code:
struct X
{
struct Y *y;
};
struct Y
{
char *A
char *B
};
in main this what I have done
Code:
int main()
{
int size = 100;
struct X **x = createX(size);
if(x == NULL || (*x)->y == NULL)
{
printf("Critical Error! ran out of memory.");
return EXIT_FAILURE;
}
freeMem(x);
}
I call createX so I can allocate some memory.
Code:
Struct X ** createX(int size)
{
struct X **x = malloc(size * sizeof(struct X *));
if(x == NULL) return NULL;
(*x)->y = malloc(size * sizeOf((*x)->y));
if((*x)->y == NULL)
{
free(x); //We free because we allocated n pointers
return NULL;
}
int i;
for(i = 0; i < 10; i++)
{
x[i] = malloc(sizeof(struct X));
if(x[i] == NULL) // If we dont't have enough memory for the pointers to point to a struct X
{
free((*x)->y);
free(x);
return NULL;
}
}
return x;
}
Call freeMem to deallocate
Code:
void freeMem(Struct X **x)
{
int i;
for(i = 0; i < 10; i++)
{
if(x[i] != NULL) // we dont want to free(NULL)
{
free(x[i]); // free allocated structure
}
}
if(players != NULL)
{
free((*x)->y); // free the pointer to struct Y
free(x); // free up all the pointers
}
}
That's it. Is there anything I did wrong or forgot to do or even added stuff that I didn't need to?