Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic array without malloc?

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.

like image 232
C-W-M-Oliver8012 Avatar asked Dec 18 '20 12:12

C-W-M-Oliver8012


1 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.

like image 93
Sourav Ghosh Avatar answered Sep 20 '22 23:09

Sourav Ghosh