News for hackers. Stuff that matters.
Re:Everything I wish I knew when learning C by IgorPartola on Monday November 28, 2022 @10:13PM (#33783259)
IIRC this is valid in C99:

    void foo(size_t n) {
        int arr[n];
        …
    }
Re:Everything I wish I knew when learning C by LegionMammal978 on Monday November 28, 2022 @11:08PM (#33783583)
VLAs can be declared in a single statement, but they cannot be initialized in C17 (6.7.9):

> The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

Curiously, C23 actually seems to break the O(1) rule, by allowing VLAs to be initialized with an empty initializer:

  int arr[n] = {};
GCC generates a memset call (https://godbolt.org/z/5v31bKs5a) to fill the array with zeros.
Re:Everything I wish I knew when learning C by throwaway2037 on Tuesday November 29, 2022 @05:29AM (#33785826)
How do you think it works? Does the compiler generate some kind of stack alloc?

Stupid question: Does that mean a huge value for 'n' can cause stack overflow at runtime? I recall that threads normally get a fixed size stack size, e.g., 1MB.

Re:Everything I wish I knew when learning C by IgorPartola on Tuesday November 29, 2022 @06:44AM (#33786333)
It just moves the stack pointer by n which is O(1). It doesn’t initialize it of course. But my point is that the array size isn’t known at compile time.
Re:Everything I wish I knew when learning C by jcelerier on Tuesday November 29, 2022 @10:43AM (#33788911)
Yes, it causes stack overflow at runtime. Compilers warn for it, in particular clang has a warning that you can configure to pop up whenever the stack usage of a function goes beyond some limit you set - I think that setting it to 32k or 64k is a safe and sane default as e.g. macOS thread stack sizes are just 512kb