recently I was given a code in C language to continue developing a new programming language and I found some instructions that caught my attention on how to declare an array and use it, but I had already seen them before. Attached is an example of the situation in code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int *lista = (int *)malloc(sizeof(int *));
lista[0] = 1;
lista[1] = 2;
lista[2] = 3;
printf("%d, %d, %d", lista[0], lista[1], lista[2]);
return 0;
}
I don't know if someone could explain to me how arrays work in this way with pointers since I can't imagine it, because the list variable supposedly contains the memory address where an integer is stored, but why can I store a list there?
This is a perfect example of something not to do in C.
That line reserves space for a single pointer of type
int
. the problem? That space should be reserved forint
... but ... why? Basically because in 32-bit architectures, as muchint
asint*
they occupy 4 bytes... but in 64-bitint
it occupies 4 bytes while itint*
will occupy 8... you are not reserving the space you need but a different one... if you reserve more you waste memory, while if you underreserve or hog memory or the OS kills your app.But if the reservation is already problematic, its use is no less harmful:
As we have seen before, it was reserving space for one or two
int
... although the idea was to reserve for only one element... and yet we are treating the reservation as if it had space for 3 elements... do you see the problem? The reserve is too small and we have seen before what can happen:The reservation should have been like this:
That is, we tell
malloc
it to provide us with memory to store 3int
.A program makes use of two different memories: stack and heap . There are actually more regions but those are already hardware and software architecture dependent and won't always be available so I won't mention them here.
The stack is the stack. The resources stored here are automatically destroyed when they are no longer needed... this memory zone is the one you learn to use first:
This memory area has serious space restrictions, so it is not suitable for storing large collections of data because if it fills up the program will stop working.
The heap is the dynamic memory region. The management of this memory falls to the programmer. This memory will be as large as the memory available on the computer. This memory is always accessed by pointers: