0

Using MinGW C compiler, this code crashes my program. NN has value 439470944 and NN and j are initialized as long-integers.

float *F=NULL;
F = (float *)malloc(NN*sizeof(float));

for(j=0; j<NN;j++)    F[j] = 0; // ensure F[] starts empty.
yonderuyo
  • 1
  • 2
  • 4
    and how is `F` declared? – ouah Jul 30 '14 at 15:17
  • Use exception handling (try, except) over F[j] to be clearer about the problem. – sbhatla Jul 30 '14 at 15:19
  • 1
    Welcome to Stack Overflow. Please read the [About] page soon. Note that you've omitted the key information, which is the declaration of array `F`. Most likely, you have it allocated on your stack, and your array is therefore around 3 GiB in space, and it is simply too big for your stack. The stack is usually limited to 8 MiB or less (less on Windows). If you aren't compiling in 64-bit mode, it is getting close to too big to manipulate even if it is a static variable or if it is dynamically allocated. – Jonathan Leffler Jul 30 '14 at 15:21
  • 6
    Check the allocation to make sure that `F` is set to a non-NULL. When there is not enough contiguous memory in the heap, `malloc` returns `NULL`. Another note: you do not need to cast `malloc` in C. – Sergey Kalinichenko Jul 30 '14 at 15:25
  • 3
    @sbhatla The question is tagged C. – Pascal Cuoq Jul 30 '14 at 15:26
  • Is it possible to check the allocation of a pointer in c? This says I can't: http://stackoverflow.com/questions/1576300/checking-if-a-pointer-is-allocated-memory-or-not – yonderuyo Jul 30 '14 at 15:36
  • 1
    This link is unrelated to your question, you don't need to check if an arbitrary pointer holds a valid address, it's enough to check if `malloc` succeeded, which can be done by testing the return value for being non-0 (if your OS isn't overcomitting memory, e.g. modern Linux systems usually are by default). And probably better you allocate a smaller piece of memory. What are you going to do with `F`? – mafso Jul 30 '14 at 15:52
  • 2
    You can check whether the allocation was successful in the function where you wrote the `malloc()` by testing whether the pointer returned by `malloc()` was NULL or not — and in that function you know that the memory was allocated. Once you pass it to other functions, those other functions cannot (reliably and portably) determine whether the memory was allocated on the stack or in the data or bss sections of the code, or in the heap managed by `malloc()` et al. But the correct place to do the checking is in the code that does the allocating. Are you building a 32-bit or 64-bit program? – Jonathan Leffler Jul 30 '14 at 15:53
  • 1
    Why do you cast? In C there is no need to cast the result of `malloc()`. Remove the cast. – alk Jul 30 '14 at 17:00

0 Answers0