Search code examples
c++cmemory-leakssegmentation-faultrealloc

Realloc used in a loop


I am trying to simulate the behaviour of vector container when push_back is used. I have created an array of pointers. Each element can have different length, so I need to reallocate every time a new element is stored:

   void *reallocf(void *p, size_t s)
{
    void *tmp = realloc(p, s);
    if(tmp) return tmp;
    free(p);
    return NULL;
}
int main(){
   int rows = 9000;
   int cols = 23000; 
   int *matrix = (int*)malloc(sizeof(int)*rows*cols);

   //counter of elements
   int *nums = new int [rows];
   memset(num, 0, sizeof(int)*rows)

    /* populate matrix*/
            ....
   int **Xcc = new int *[rows];


  for(i = 0; i < rows; i++){
      for(k = 0; k < cols; k++){
          if(matrix[i*cols +k] == 0){
             Xcc[i] = (int*) reallocf(Xcc[i], sizeof(int)*(num[i]+1));
             Xcc[i][num[i]] = k;
             num[i]++;
          }
       }
   }

}

Basically what I am doing is storing the position of an element that is 0. So, the array Xcc[i] is increase by one element every time is needed. The new length will be previous one plus 1, which is going to be stored.

Apparently seems to be fine to me, however it depends on something that I am getting segmentation faults and after looking at it from many different angles I am currently stuck. Any help would great, ideas or suggestions.


Solution

  • Probably the problem is this: when you do

    int **Xcc = new int *[rows];
    

    Xcc[i], for a generic i, is not initialized, then a call to realloc() may sometime work (if Xcc[i] is null) and sometime may not (segfault).

    You are missing a:

    memset(Xcc, 0, sizeof(int*) * rows);