Richard Heathfield <> writes:
> Dr Dav said:
>
> <snip>
>>
>> 1. Are arrays of size 300x300 large enough to overwhelm the space
>> available on the stack (if relevant my machine is an Intel Core 2 Duo
>> running linux)?
>
> Typical double on a modern desktop system, is 8 bytes. 8 * 300 * 300 is
> a mere 720,000 bytes. Nowadays, that's peanuts for *dynamic*
> allocation, but could easily cause problems with static allocation,
> yes.
[big snip]
There are three storage durations, automatic, static, and allocated.
Automatic storage duration refers to objects declared locally within a
function or block (sometimes referred to as "stack"). Static storage
duration refers to objects that exist throughout the lifetime of the
program; they're declared with the keyword "static" or outside any
function. Allocated storage duration refers to objects allocated by
calls to malloc (or calloc, or realloc) (sometimes referred to as
"heap"),
An implementation is likely to place different limits on these three
kinds of storage duration; automatic duration often has the lowest
limit. As long as you can deal with the differing semantics,
switching from automatic to static storage duration *might* solve your
problem.
Some systems also provide ways to change memory allocation limits,
either system-wide or for a single process. <OT>On Unix-like systems,
see "limit" or "ulimit">,<OT>
Also, if the bounds of your arrays are constant and you choose to use
dynamic allocation (malloc), that can simplify your code. Many
examples of dynamic allocation of two-dimensional arrays are designed
to allow for both dimensions being determined at execution time. If
you know in advance that you want your arrays to be exactly 300 x 300,
you can use a single allocation. For example:
#include <stdio.h>
#include <stdlib.h>
#define MATRIX_SIZE 300
typedef double matrix[MATRIX_SIZE][MATRIX_SIZE];
int main(void)
{
matrix *m;
int i, j;
m = malloc(sizeof *m);
if (m) {
printf("Allocated %lu bytes\n", (unsigned long)sizeof *m);
}
else {
fprintf(stderr, "Allocation failed\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < MATRIX_SIZE; i ++) {
for (j = 0; j < MATRIX_SIZE; j ++) {
(*m)[i][j] = i + j;
}
}
printf("(*m)[123][234] = %g\n", (*m)[123][234]);
return 0;
}
--
Keith Thompson (The_Other_Keith)
kst- <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"