how do i dynamically allocate memory to a variable at runtime?

You can’t dynamically allocate static storage. You need to use the stack, or malloc / mmap / whatever (sometimes called the “heap”). (Unless you just make a huge array in the .bss, where you should have put this instead of .data, and only use however much you need. Lazy memory allocation by the kernel makes that fine.)

You can keep a pointer in static storage, like C static int *p;, but then you need to go through the extra layer of indirection every time you access it.

A variable-sized allocation on the stack is what compilers do for alloca, or for C99 variable-length arrays. Look at compiler output for how they round the allocation size up to a multiple of 16 to keep the stack aligned. (And how they address that storage relative to the new value of the stack pointer.)

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top