Search code examples
c2ddynamic-memory-allocationrealloc

A 2D array reallocation in C


I know this has been discussed here plenty of times, but I simply cannot see what I'm doing wrong. Here's the snippet.

#include <stdio.h>
#include <stdlib.h>

double** SEG = NULL;

void main ()
{
    int i;
    int seg_counter = 0;

    SEG = (double**) malloc(1 * sizeof(double *));
    for(i=0; i < 1; i++)
        {
        *(SEG + i) = (double*) malloc(9 * sizeof(double));
        }

    while (1)
        {
        SEG = (double**) realloc(SEG, seg_counter+1 * sizeof(double *));
        for(i=seg_counter; i < seg_counter+1; ++i)
            {
            *(SEG + i) = (double*) malloc(9 * sizeof(double));
            } 
        printf ("%d\n", seg_counter);
        seg_counter++;
        }
}

The goal is to add one row each time the loop is executed. I'm getting a memory error instead. Thnx for any help here!


Solution

  • For starters you should set the variable seg_counter to 1 after this memory allocation

    int seg_counter = 0;
    
    SEG = (double**) malloc(1 * sizeof(double *));
    
    ++seg_counter;
    

    Or you could write

    int seg_counter = 1;
    
    SEG = (double**) malloc( seg_counter * sizeof(double *));
    

    Then the following for loop (that is in fact redundant) will look like

    for(i=0; i < seg_counter; i++)
        {
        *(SEG + i) = (double*) malloc(9 * sizeof(double));
        }
    

    This statement

    SEG = (double**) realloc(SEG, seg_counter+1 * sizeof(double *));
    

    has a typo, You need to write

    SEG = (double**) realloc(SEG, ( seg_counter+1 ) * sizeof(double *));
    

    Again the next for loop is redundant. You could just write

            *(SEG + seg_counter) = (double*) malloc(9 * sizeof(double));
    

    and then

        seg_counter++;
        printf ("%d\n", seg_counter);
    

    As you have an infinite while loop then your program will be aborted when memory can not be allocated.