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!
A couple of options:
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);
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.