void mmalloc(void ***matrix, size_t n, size_t m)
{
register unsigned long int i, j;
if (matrix == NULL)
return;
*matrix = malloc(n);
if (*matrix == NULL)
return;
for (i = 0; i < n; ++i) {
*((*matrix)+i) = malloc(m);
if (*((*matrix)+i) == NULL)
break;
}
if (i < n+1) {
for (j = 0; j <= i; ++j) {
if (*((*matrix)+j) != NULL)
free(*((*matrix)+j));
}
free(*matrix);
}
return;
}
void mfree(void **matrix, size_t n)
{
register size_t i;
for (i = 0; i < n; ++i)
free(*(matrix+i));
free(matrix);
}
void **mrealloc(void **matrix, size_t n, size_t m, size_t nsize, size_t msize)
{
return NULL;
}
#endif
When I'm back from 2 weeks vacation, I'll bet that /prog/ (even the wizards) haven't solved this mystery. The amount segfault and other corruptions I got from my own code was amazing. Enjoy.
Name:
Anonymous2011-08-03 18:21
>>4
Outstanding sir. I must say, I feel pretty stupid of not realising such a simple solution. Still, I'm bothered by my own solution. I can allocate a matrix, but the mfree'ing makes the program abort and I know that there is a grave design error somewhere, but I can't figure it out. Could somebody give me a hint?
I rewrote the code again today (with the flaw still being there):
auto unsigned int i, j, n = 5, m = 5;
auto unsigned int **matrix = (unsigned int **) mmalloc(sizeof(*matrix)*n,sizeof(**matrix)*m);
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j)
matrix[i][j] = i+j;
}
for (i = 0; i < n; ++i) {
for (j = 0; j < m; ++j)
printf("%4u%c",matrix[i][j],j+1<m?' ':'\n');
}
mfree((void *) matrix);
matrix = NULL;
return 0;
}