How does malloc organize memory?

1

When I allocate memory with malloc() , are the addresses equal to a vector? Or are they scattered in the memory of the PC?

I want to create a list of structs , to do this, I have to have several structs in case, can I do this just by allocating memory with ( malloc() ) or is there another way to do it? p>

Example:

int n=7,cout;
Node *lista;  <- Essa lista Node vamos supor que eu tenha criado antes do main.
for(cout=1;cout<=n;cout++){
    lista = (Node*)malloc(sizeof(Node)*n);
}

I did this to create 7 nodes.

When doing this, am I actually using the list concepts? And if I want to bind my pointer that is in struct to another node, how do I identify the other node since all are of type Node and have the same name? And what does malloc() differ from a vector? But I ask this not in the sense of a static being and another dynamic, but in the positions of memory.

    
asked by anonymous 10.11.2017 / 18:07

1 answer

1

Allocation by malloc() is same as array from the point of view of the question, it's all continuous, when allocating a data string .

Well, physically it may not be so because of virtual memory, but this does not matter to your program, it will see the addresses as if they were continuous.

What changes is the storage location, malloc() will allocate in the heap and the array will allocate to the stack (unless that it is part of another structure that goes in heap , because the array is not allocating in fact, it is only reserving space in another structure). Technically, the 'stack' is a data structure, so the array is always reserving space. It is true that the heap also, but the structure is external to the application, so it really is an allocation.

If you are doing isolated allocations, there is no guarantee of where each of them will be accessed, so they may be scattered, although it is likely that it is not, in most simple situations, which can be misleading because people do not they care about doing right, just making things work, which are very different things.

This code does not seem to make sense. I think that's all you want:

Node *lista = malloc(sizeof(Node) * 7);

But if you do:

for (int i = 1; i < n; i++) Node no[i] = malloc(sizeof(Node));

It no longer guarantees that the allocation will be continuous.

If you're doing a linked list , you probably want something else, but also different from what's in the question .

There are several ways to allocate memory, it depends on what you need.

Study:

I did not answer the rest because they are other questions, do it separately. Even because they do not have enough information to respond.

    
10.11.2017 / 18:22