0

With the following:

#include <stdlib.h>
int main() {
    long n = 20e6;
    float values[n];
    for(long i = 0; i < n; i++)
        values[i] = 0;
    return 0;
}

I get Segmentation fault: 11. But with the following:

#include <stdlib.h>
int main() {
    long n = 20e6;
    float *values = malloc(n*sizeof(float));
    for(long i = 0; i < n; i++)
        values[i] = 0;
    return 0;
}

Not. Why?

KcFnMi
  • 5,516
  • 10
  • 62
  • 136
  • Simply because the first one try to allocate the array on the stack. Just curious what compiler and linker are you using? Or simply you paid no attention to warnings? – Frankie_C Apr 22 '18 at 15:14
  • I'm doing `gcc -g -Wall main.c` on macOS, without any warnings. What can I do to see the warnings? – KcFnMi Apr 22 '18 at 15:16
  • @Frankie_C I get no warnings on this code, neither with gcc nor clang. – Steve Summit Apr 22 '18 at 15:21
  • Use `-fstack-check` on GCC. Unfortunately it is normally not active (see https://gcc.gnu.org/onlinedocs/gcc-3.4.2/gnat_ugn_unw/Stack-Overflow-Checking.html). By experience when working with an OS normally you should be aware of standard stack dimensions. On some OS's the linker has switches to enlarge stack. @SteveSummit. – Frankie_C Apr 22 '18 at 15:24
  • @Frankie_C Thanks for the tip about `-fstack-check`; I didn't know that. I had tried with `-Wall`, which didn't complain. On my (MacOS, like the OP's) system, `-fstack-check` doesn't warn, either. Yet it crashes for me too, same as the OP. So it seems these warnings aren't a panacea. – Steve Summit Apr 22 '18 at 15:58
  • @SteveSummit Unfortunately this surprised me too. By default no compiler triggers any warning for possible stack overflow, and even the linker seems to be unaware of stack dimensions. Just runtime checks are available to rise exceptions during execution. – Frankie_C Apr 22 '18 at 16:06
  • @SteveSummit I didn't know, as I said this surprised me too. I would have bet that there was a warning. Should I remove comment? I can't modify it anymore. – Frankie_C Apr 22 '18 at 16:23
  • 1
    @KcFnMi Sorry, but you couldn't have seen any warning because none would be emitted. Anyway, as I said before, be aware to declare large amount of data in automatic variables because them will be allocated on the stack, that is normally limited to 1 or more few Mbytes. – Frankie_C Apr 22 '18 at 16:43

0 Answers0