Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: how to manage a large structure?

In C:

I am trying to use a structure containing a large array, and I have a stack overflow error while declaring it. I guess (correctly?) that I don't have enough memory in the stack, and therefore, I should use the heap (I don't want to change my stack memory size, as the code will be used by others). Could anyone show me a way to do it simply? Or should I use something else than a structure?

My code - definitions.h:

#define a_large_number 100000

struct std_calibrations{
    double E[a_large_number];
};

My code - main.c:

int main(int argc, char *argv[])
{
    /* ...
    */

    // Stack overflows here:
    struct std_calibrations calibration;

    /* ...
    */

    return (0);
} 

Thank you for your help!

like image 488
user2076688 Avatar asked May 21 '13 14:05

user2076688


2 Answers

A couple of options:

  1. Use malloc(3) and free(3) to dynamically allocate your structure at runtime. This option is what you're talking about when you say you "should use the heap."

    struct std_calibrations *calibration = malloc(sizeof *calibration);
    

    and later,

    free(calibration);
    
  2. Give the structure static storage duration. Either add a static keyword or make it global. This option may change some semantics about how you use the structure, but given your example code, it should be fine.

like image 50
Carl Norum Avatar answered Nov 07 '22 21:11

Carl Norum


Change the member E to be a double* and malloc() memory for it:

struct std_calibrations calibration;
calibration->E = malloc(sizeof(*calibration->E) * a_large_number);

and remember to free(calibration->E); when no longer required. It would be possible to extend struct std_calibrations, if desired, to contain the number of elements in E so a user of struct std_calibrations could decide how many elements they require.

like image 21
hmjd Avatar answered Nov 07 '22 22:11

hmjd