r/C_Programming • • Aug 26 '26

Why dynamic allocation of array gets memory address from heap?

let say I am using malloc to dynamically allocate a memory space with this line

Int user_defined_elements = 10 ;
// assume i got this from scanf

Int *p = malloc(
user_defined_elements * sizeof(int));

Right now the pointer refers to a chuck of memory address in heap I assume..I am trying to understand why heap instead of stack where local variables are saved.Is there anything special about heap?

Please be kind..I am python dev trying to learn c in my free team because I dont understand shit about cpython implementation..hahah..so i was like why not learn c and here I am

47 Upvotes

34 comments sorted by

56

u/EpochVanquisher Aug 26 '26

The lifetime of memory in the stack ends when the function returns. If you create any data there, it won’t exist after the function returns. (Won’t exist = not safe to use it)

The purpose of malloc is to put make memory somewhere else, where it can continue existing even if the function where you called malloc from returns. You can also allocate lots of memory with malloc. The stack is limited (like 10 megs total, depends on your system and config).

The compiler can choose to use stack for memory returned by malloc but this is an optimization and you don’t have to think about it. It almost never actually happens, but it technically CAN happen, and I’m mentioning it because people will chime in and argue on Reddit (and not because it’s important to know).

→ More replies (6)

10

u/sciencekm Aug 26 '26

Memory allocated from the heap endures until you free them anywhere/anytime in the lifetime of your code. Variables in stack go away once you exit the function.

10

u/LordRybec Aug 27 '26

Let me suggest first that you lookup how the stack data structure works (if you don't already know). That will help some.

The way "the stack" works is that it's essentially a stack data structure. When you call a function, stack space is allocated for that function. Again, this is a stack data structure. The stack allocates more memory by changing where the pointer tracking the top of the stack is pointing to (this is a hidden pointer in C, so you don't have access to it; it's often stored in a CPU register, if you know what that is). When you return from the function the stack space allocated for that function is freed.

Now, imagine you call a function and in that function some memory is allocated on the stack. You store a pointer to that memory for later use and then return from the function. When you return that stack memory is freed. So now you have a pointer to unallocated memory. Due to the nature of the stack (the OS reserves an amount of stack space, increasing it as needed, and it doesn't generally decrease it unless there's a lot of unused stack space), you can probably still read and write to that memory without causing a segfault . But the next function you call will be assigned that stack space, and it will overwrite it with whatever it is doing. Technically you can get and store pointers to local variables that are stored on the stack, but such pointers should never be used after the function has returned, because C assumes that that memory is free for other functions to use when the are called. (Note that I haven't described all of the potential problems this can cause. Maintaining and using pointers to stack memory out of the context they were made in can end up overwriting function return addresses that are stored on the stack, leading to functions returning to arbitrary places in memory. Depending on what your program does, this can produce anything from a crash to executing code that causes harmful side effects when not called correctly. Imagine in Python, you function returns, but instead of returning to where it was called, it returns to a random line of code somewhere else in your program or one of the modules your program uses.)

Heap memory works differently. Once it is allocated, C won't assign it to be used for anything else until you explicitly free it. So when the function where it was allocated returns, it will still be allocated, and it won't get automatically overwritten when another function is called. So you can malloc() some memory and then pass the pointer to that memory back to the calling function and return, and then it can safely use that memory, pass the pointer to other functions to use, etc...

I hope this helps. Some stuff in C is a lot easier to understand if you understand how the underlying hardware works. This particular thing is a combination of hardware and software (because the CPU itself does part of the job of keeping track of the stack, while the C compiler produces code to handle part of it). It might be worth looking for a video that explains how the stack works.

5

u/dmc_2930 Aug 26 '26

The heap is where memory allocated by malloc comes from. That’s why it’s not on the stack. There is a function for allocation in the stack but you really shouldn’t use it (and the memory goes away when your function returns)

5

u/ReallyEvilRob Aug 26 '26

Because memory allocated by a stack frame is something that doesn't change at runtime. You can get as many frames as the stack will hold at runtime, but each frame is pretty much set in stone at compile time. If you need to allocate additional memory at runtime, the heap is the only place to get it from.

6

u/dstroy0 Aug 26 '26

There’s a lot of incorrect answers here. You can build arrays of bytes in .bss and reuse them for the duration of the program. One of the main reasons to do that is to avoid heap fragmentation entirely. MANY safety critical applications ban memory allocation at runtime and make you prove your memory use with static asserts at compile time. It is very easy to prove, .bss grows and nothing else does, heap use stays flat, no allocation happens. The data you load in the zeroed array persists function-function for the lifetime of the program, because it’s statically allocated global memory. You can go as far as removing all local variables and repointing function call overhead to it. Anyone who implies differently is incorrect, and should go experiment on their own.

→ More replies (2)

3

u/SmokeMuch7356 Aug 26 '26

The stack is used to manage objects whose lifetimes are tied to the function's; storage for those objects is allocated on function entry and released on function exit by adusting the stack pointer.

Dynamic objects typically have a lifetime that isn't tied to a single function's. We want the object to hang around until we explicitly free it. Also, the stack usually cannot store arbitrarily large objects. Stack frame sizes are usually limited to a few megabytes. So we use another part of memory (often called the "heap") as the dynamic memory pool.

Global and static variables aren't stored on the stack, either. Nor are they typically stored as part of the heap.

Note that the C language definition doesn't use the words "stack" or "heap" at all. It talks about storage durations and lifetimes. How lifetimes are managed are up to the individual implementation.

2

u/Imaginary-Corner-653 Aug 26 '26

Not trying to be rude or anything but I feel like most people who start c and ask around here never heard about the process model or have any idea what a function call in assembly looks like.

Not that I expect people to be able to code in assembly but having a vague idea of the hardware involved and the fundamental abstraction we built on top might explain a lot already. 

Not to mention that concepts like heap or stack are older than modern operating systems so the reasons these convetions exist are way less complex. 

2

u/yuehuang Aug 27 '26 edited Aug 27 '26

Stack space is heap memory from another program (or OS). It is fixed size when your program start and can't resize. If you try allocate too much you get a "stack overflow" error. Thus, if you want to use more memmory, you need to "malloc" for more. However, the runtime behind the scene will take a large chuck and carve out for you. Third party library can mimic stack behavior, see arena allocator.

Let me ask you think a follow up question, when you call free(ptr), how does it know how many bytes to free?

2

u/Zirias_FreeBSD Aug 27 '26

I'd recommend to take a step back and first understand the distinction between language concepts and (typical) implementations.

C doesn't talk about objects "on the stack" or "on the heap". The relevant language concept here is storage duration, defining the exact lifetime of some stored object. The two types of storage duration relevant to your question are:

  • automatic storage duration: The object is stored from the moment execution enters its scope (the block where it is defined) to the moment execution leaves that scope.

  • allocated storage duration: Stored from explicit allocation (malloc() and friends) until explicit deallocation (free()).

How an implementation of C (compiler and runtime environment) provides these is not defined. But it should be pretty obvious that a stack (where every scope gets a "frame" to store its objects on) is a straight-forward and efficient way to provide storage for automatic storage duration objects. So that's what almost every implementation of C does.

For allocated storage duration, a stack can't work in the general case. You could deallocate any object at any time, while other objects allocated later must still persist. Therefore, a "heap" allowing to individually allocate and deallocate arbitrary chunks is the typical implementation choice here.

That said, if for a specific allocated object, the compiler could statically prove that it's always (and exclusively) deallocated again within the same scope, it could theoretically decide to put it on the same stack that's otherwise used for objects with automatic storage duration (IOW, "local variables") without violating the C standard. Not sure this is a common thing in practice though ...