0

On Apple clang version 12.0.5 (clang-1205.0.22.11) with gcc -ansi the following produces a segfault:

#include <stdlib.h>

#define ARG_MAX 1024 * 1024

struct S { const char *array[ARG_MAX]; };

int main(void) {
    struct S as[] = {{NULL}};
    return EXIT_SUCCESS;
}

ARG_MAX is defined in sys/syslimits.h as 1024 * 1024, defined above explicitly.

How do I avoid the segfault?

Samuel Marks
  • 1,611
  • 1
  • 20
  • 25

1 Answers1

0

Large arrays with automatic storage duration (aka local variables) is to be avoid on most implementations as they typically use a stack with a fixed and rather limited size, e.g. in the rang 1-8 MB. If the object size exceeds the available stack, all kind of things may happen. Including seg fault.

How do I avoid the segfault?

Use dynamic allocation like:

#define ARG_MAX (1024 * 1024)

struct S { const char *array[ARG_MAX]; };
int main(void) {
    struct S * as = calloc(1, sizeof *as);
    if (as == NULL) exit(EXIT_FAILURE);

    ... use as[0] ...

    free(as);
    return EXIT_SUCCESS;
}

Most implementations have much more memory available for dynamic allocated objects. It's typically called heap memory.

BTW: It's legal but a bit strange that your code makes an array with a single element.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Note that the zero-initialization afforded by `calloc()` is not necessarily equivalent to the effect of the OP's initializer, because a pointer whose representation has all bits zero is not necessarily a null pointer. And if it is a null pointer, it's not necessarily the *same* null pointer value that would be obtained via the initializer. There can be multiple null pointer representations, though they must compare equal to each other. – John Bollinger Aug 18 '21 at 05:20
  • My reason for using `ARG_MAX` is to specify the longest CLI argument possible; without using dynamic allocation. But on macOS the whole `1024*1024` limit is just ridiculously large. Is there a different `#define` I should be using on macOS? – Samuel Marks Aug 18 '21 at 10:08
  • @SamuelMarks It's unclear to me what you are trying to do. Stack size and number of program arguments is not related – Support Ukraine Aug 18 '21 at 10:28