-2

I need to read an indefinite number of digits from standard input and write them to an array, but when reading 1050 numbers, the program crashes.

#include <stdio.h>

int main() {

    int length;
    scanf("%d", &length);
    printf("\nLength = %d\n", length);

    int array[length];

    for (int i = 0; i < length; i++) {
        scanf("%d", &array[i]);
    }

    printf("\nAll data are scanned\n");

    for (int i = 0; i < length; i++) {
        printf("%d, ", array[i]);
    }
    return 0;
}
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
  • 4
    This is not "dynamic memory allocation", you know that, right? – Sourav Ghosh Oct 08 '22 at 12:38
  • @SouravGhosh Well the array is allocated at run-time, so it's in a way "dynamic"... :) – Some programmer dude Oct 08 '22 at 12:46
  • @Bobikwerty Arrays, compile-time or variable-length arrays (like the one you have created), are usually allocated and created on the *stack*. The stack is a limited resource, on Windows it's only one single MiB by default, on e.g. Linux 8 MiB. Now take your size (the number of elements) and multiply with the size of `int` (`sizeof(int)`, usually 4 bytes) and you'll get the number of bytes needed. Will it fit? – Some programmer dude Oct 08 '22 at 12:48
  • 1
    Also, if you want (theoretically) "infinite" values you need to use `malloc` and `realloc` to create and recreate your array as numbers are added. But note the "theoretically" bit, because no computer in history have infinite memory. – Some programmer dude Oct 08 '22 at 12:50

1 Answers1

2

Because your array is being allocated on the stack, you're causing a stack overflow which crashes your program. You can use malloc() to allocate memory on the heap. As an alternative, you can make it static.

Consider reading this. It is good reading for understanding data segments.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
erenalyoruk
  • 121
  • 4