-1

I have the following code:

#include<stdio.h>

int main(void){
  int x[20000000];
  return 0;
}

Compiling it as gcc file.c, and running it works flawlessly.

However, compiling it as gcc -fsanitize=address -fsanitize=undefined file.c gives the following error:

AddressSanitizer:DEADLYSIGNAL
=================================================================
==364==ERROR: AddressSanitizer: stack-overflow on address 0x7fffcdbeb220 (pc 0x55b9a94951a0 bp 0x7fffce3ea220 sp 0x7fffcdbeb220 T0)
    #0 0x55b9a949519f in main src/gbarray.c:3
    #1 0x7efd3f2320b2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
    #2 0x55b9a94950cd in _start (/mnt/d/duart/Documents/personalProjects/Random/garbageArrayValue/bin/garbageArray+0x10cd)

SUMMARY: AddressSanitizer: stack-overflow src/gbarray.c:3 in main
==364==ABORTING

What is happening here and how do I solve this issue?

  • 1
    Stack size is limited, allocate large arrays on the heap. – HolyBlackCat Jul 24 '21 at 13:53
  • 2
    Local variables are usually put on the stack, and that includes arrays. The stack is a limited resource, on Windows it's only a single MiB, on Linux the standard stack size is 8 MiB. Your array is almost 80 MiB (using the common `sizeof(int) == 4`). – Some programmer dude Jul 24 '21 at 13:53
  • With the explanation out of the way, what is the purpose of this large array? One very seldom need such large arrays. If you want to store large amount of data there might be better data-structures or algorithms. – Some programmer dude Jul 24 '21 at 13:54
  • @Someprogrammerdude I just answered another question on SO, and the array had that size. When I tried compiling it with my flags, the error happened. –  Jul 24 '21 at 13:55
  • 1
    In [the original question](https://stackoverflow.com/q/68507861/440558) the array was a tenth of the size (you mistakenly added a zero) *and* it's an array of `char`. That means the size was only a little less than 2 MiB, not almost 80 MiB as your array. :) – Some programmer dude Jul 24 '21 at 14:27
  • 1
    Without ASAN, the memory in the array is never touched, so even though it exceeds the stack space, the program probably won't crash (barring signal handlers, etc). Add `x[0]=5;` to your program and see the difference. (On the other hand, if you enable optimizations, the whole thing will likely be optimized out as it has no effect on the program's behavior, so the crash will go away again.) – Nate Eldredge Jul 24 '21 at 15:09

1 Answers1

0

What is happening here

Stack overflow.

how do I solve this issue?

Allocate less memory on stack or increase allowed/available stack size.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111