-1

I have written a code like this:

int * ptr;
ptr = (int*) malloc(5 * sizeof(int));

Please tell me how memory is allocated to "ptr" using this malloc function? How is it different from memory allocation in an integer array?

  • 4
    Possible duplicate of [Difference between declaration and malloc](https://stackoverflow.com/questions/10575544/difference-between-declaration-and-malloc) – rma Jun 23 '17 at 07:46
  • 2
    [Also casting malloc is bad](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Ed Heal Jun 23 '17 at 07:50

2 Answers2

6

1. Answer in terms of the language

It differs in the storage duration. If you use an integer array, it could be at the file scope (outside any function):

int arr[5];

This has static storage duration, which means the object is alive for the whole execution time of the program.

The other possibility is inside a function:

void foo(void)
{
    int arr[5];
}

This variant has automatic storage duration, so the object is only alive as long as the program execution is inside this function (more generally: inside the scope of the variable which is the enclosing pair of braces: { ... })

If you use malloc() instead, the object has dynamic storage duration. This means you decide for how long the object is alive. It stays alive until you call free() on it.

2. Answer in terms of the OS

malloc() is typically implemented on the heap. This is an area of your address space where your program can dynamically request more memory from the OS.

In contrast, with an object with automatic storage duration, typical implementations place it on the stack (where a new frame is created for each function call) and with static storage duration, it will be in a data segment of your program already from the start.

This part of the answer is intentionally a bit vague; C implementations exist for a vast variety of systems, and while stack, heap and data segments are used in many modern operating systems with virtual memory management, they are by no means required -- take for example embedded platforms and microcontrollers where your program might run without any operating system. So, writing portable C code, you should (most of the time) only be interested in what the language specifies.

4

The C standard is very clear on this.

  1. The memory pointed to by ptr has dynamic storage duration.

  2. The memory associated with an int foo[5];, say has automatic storage duration.

The key difference between the two is that in the dynamic case you need to call free on ptr to release the memory once you're done with it, whereas foo will be released automatically once it goes out of scope.

The mechanism for acquiring the memory in either case is intentionally left to the compiler.

For further research, Google the terms that I've italicised.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483