To create an object it is not necessary to call malloc()
, even because it is made to allocate dynamic memory, only that. It allocates memory and returns an address where there was allocation. Creating and placing an object there is another separate operation, usually will be done with the assignment operator (=
) or a function that does the same.
The comment that says use the structure Pessoa
is mistaken, because there is no object there, at least not one initialized, so there is only garbage, you can even access that place as if you had, but in practice you will be collecting garbage.
Inclusive it makes no sense to do the cast in function.
It is easier to make the second option, if it is what you want. If you want to allocate in automatic memory is much easier, even because then you will not have to release the allocation made with malloc()
. But this allocation is only available for this function, does not allow the object to survive the end of the function, nor can it be used elsewhere. In many cases this is enough, in other cases not, dynamic allocation is necessary when you do not know how long it should survive or if you know it is beyond the limit from where it was created. In some cases size may be the determinant. But this can be seen below.
You can read more on:
And can also research more on the subject here on the site, has a lot of useful information. Already have some links available there in the questions linked. Folks missed a little bit of learning from the answers here. Tough luck.
The question changed as I answered.
So you’re saying that if I want a variable to remain indefinitely in memory, just allocate it with "malloc()"? And I see a lot of code out there in C that allocates a struct using "malloc()" and then initializes its variables using the "->" operator, and how the variables in a struct are initialized if they’re "junk," as you said?
– Luiz Fernando
When booting stops being junk.
– Maniero
So in theory it makes no difference whether to use "malloc()" or not to allocate anything? In this question that you put, the person uses "malloc()" to allocate a pointer to an int, isn’t it easier just to write the "int *ptr;"? So one should only use "malloc()" in dynamic allocation? How to allocate an array of x positions?
– Luiz Fernando
No, if you do, you’re not allocating memory. You have to read all the material and even more because you’re pulling a wire and getting into another subject.
– Maniero
Okay, I’ll read it, thanks anyway
– Luiz Fernando