Dynamic array without malloc?

Viewed 248

I was reading through some source code and found a functionality that basically allows you to use an array as a linked list? The code works as follows:

#include <stdio.h>

int
main (void)
{
    int *s;
    
    for (int i = 0; i < 10; i++)
    {
        s[i] = i;
    }
    
    for (int i = 0; i < 10; i++)
    {
        printf ("%d\n", s[i]);
    }
    
    return 0;
}

I understand that s points to the beginning of an array in this case, but the size of the array was never defined. Why does this work and what are the limitations of it? Memory corruption, etc.

3 Answers

Why does this work

It does not, it appears to work (which is actually bad luck).

and what are the limitations of it? Memory corruption, etc.

Undefined behavior.

Keep in mind: In your program whatever memory location you try to use, it must be defined. Either you have to make use of compile-time allocation (scalar variable definitions, for example), or, for pointer types, you need to either make them point to some valid memory (address of a previously defined variable) or, allocate memory at run-time (using allocator functions). Using any arbitrary memory location, which is indeterminate, is invalid and will cause UB.

I understand that s points to the beginning of an array in this case

No the pointer has automatic storage duration and was not initialized

int *s;

So it has an indeterminate value and points nowhere.

but the size of the array was never defined

There is neither array declared or defined in the program.

Why does this work and what are the limitations of it?

It works by chance. That is it produced the expected result when you run it. But actually the program has undefined behavior.

As I have pointed out first on the comments, what you are doing does not work, it seems to work, but it is in fact undefined behaviour.

In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres.

Hence, it might "work" sometimes, and sometimes not. Consequently, one should never rely on such behaviour.

If it would be that easy to allocate a dynamic array in C what would one use malloc?! Try it out with a bigger value than 10 to increase the likelihood of leading to a segmentation fault.

Look into the SO Thread to see the how to properly allocation and array in C.

Related