Question

Ok I asked this the other day. But the answers I recieved when asked made me realize I was not fit to question it yet until I did some hard research.

So here I am yet again to retry this....

In examples of malloc I seen something as such...

    #include <stdio.h>

    int main()
    {
        int ptr_doe;

        ptr_doe = (int *) malloc(sizeof(int));
    }

I read that it was not neccesary for the:

    (this *) malloc(sizeof(int));

And that only

    (int *) malloc(sizeof(\\this));

is neccesary. Is the casting before calling the malloc function ever neccesary? And how do we know how much memory we need to allocate and what the hell is this?

    malloc(10 * sizeof(int));

is it multiplying 4 bytes by 10? and when is it neccesary to use malloc? How does it work internally? Thanks for any help guys

Was it helpful?

Solution

1.

Is the casting before calling the malloc function ever neccesary?

If you use a currect compiler, No. See answers to Do I cast the result of malloc?

2.

how do we know how much memory we need to allocate

It depends on your needs.

3.

malloc(10 * sizeof(int));

means to allocate memory big enough to store 10 int value.

4.

is it multiplying 4 bytes by 10?

If sizeof(int) equals 4, yes.

5.

when is it neccesary to use malloc?

If only at runtime you can know how much memory your program needs.

6.

How does it work internally?

Briefly, malloc() will ask operating system for enough memory, record some information it needs, and return you a pointer to the start of that memory segment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top