arkkimede
arkkimede

Reputation: 105

Problems using malloc

I'm writing a C code where it is needed an array with several dimensions (e.g. 3) allocated dynamically. A minimal example could be (following the suggestion of Some Programmer Dude I reported a full minimal example that check what malloc report)

#include <stdio.h>
#include <stdlib.h>
void *malloc_chk(size_t size, char *funcName, int line);
int main()
{
   double ***v;
   int dim1=10;
   int dim2=0;
   int dim3=7;

   v = (double ***) malloc_chk(sizeof(double **)*dim1,__FILE__,__LINE__);
   for(int i=0; i<dim1; i++)
   {
      v[i] = (double **) malloc_chk(sizeof(double *)*dim2,__FILE__,__LINE__);
      for(int j=0; j<dim2; j++)
      {
         v[i][j] = (double *) malloc_chk(sizeof(double) * dim3,__FILE__,__LINE__);
      }
   }

   v[0][0][0] = 5.7; // Segmentation fault 



   return 0;
}


void *malloc_chk(size_t size, char *funcName, int line)
{
   void *ptr;
   ptr = malloc(size);
   if(ptr == NULL)
   {
      printf("Memory allocation faild.\n");
      printf("Memory size reqeusted: %zu\n",size);
      printf("Function name where the error occurs %s\n",funcName);
      printf("Line of the source code where the error occurs: %d\n",line);
      printf("Execution aborted @malloc_chk\n");
      exit(1);
   }
   else
     return ptr;
}


Some time, dim_i could be 0 and using v the running code produce Code Dump. At the moment my workaround is verify if the dim_i are null and increase to 1. Obviously this solution case a lot of problems in section where the dim_i must be 0 to obtain a correct solution. My question is: to keep the code general and not produce several part on function of one o more dim_i null, it is possible adopting a technique able to avoid core dump? Thank You in advance

Upvotes: 0

Views: 123

Answers (2)

John Bollinger
John Bollinger

Reputation: 181189

Some time, dim_i could be 0

All other considerations notwithstanding, if any dimension is 0 then there are no valid indexes for that dimension. Not even 0. That is not an issue for your loop nest, but conceptually, your assignment v[0][0][0] = 5.7 expresses an out-of-bounds access in such cases, regardless of which dimension or dimensions are 0. There are no double elements you can assign to if any dimension is 0.

Upvotes: 0

Barmar
Barmar

Reputation: 782168

The result of malloc(0) is implementation-dependent; it may return either NULL or a pointer to memory that you're not allowed to dereference; see zero size malloc. Either way, assigning to v[0][0][0] is not permitted.

You can put that assignment in a conditional to avoid this situation:

if (dim1 != 0 && dim2 != 0 && dim3 != 0) {
    v[0][0][0] = 5.7;
}

Or move the element initialization into the innermost for loop. If any of the dimensions are zero, the loop for that dimension will not execute, and the assignment will be skipped.

Upvotes: 1

Related Questions