0

I've a big doubt about when to really use heap memory. I'm studying C language and I know what memory allocation means but I didn't understand why we should use it. Yes I know that if I want to allocate an integer in the memory heap I've to use malloc function and then I've to free it to avoid memory leak but, again, why do some programmers need to allocate variables in heap memory instead of stack memory ? Sorry for my bad English, I'm trying to improve it. Thanks!

I thinks that memory heap is used when the memory stack is almost full or totally full but I'm very not sure about it.

m615
  • 11
  • 3
    (1) To allocate a large block of memory (which is not advisable to do on the stack), or (2) If you need the allocated data to out-live the stack frame (e.g. when you return from a function). – wohlstad Dec 05 '22 at 10:12
  • "I thinks that memory heap is used when the memory stack is almost full or totally full but I'm very not sure about it." Good that you don't feel sure about that... because it's wrong – Support Ukraine Dec 05 '22 at 10:16
  • Check out [What gets allocated on the stack and the heap?](https://software.codidact.com/posts/277536) for a brief summary of the various memory segments of the average program. – Lundin Dec 05 '22 at 10:17
  • 1
    Sometimes, we are not sure about how much memory to allocate. In such cases specifying an arbitrary size on stack may result in overflow or unused wasted memory. When allocating memory dynamically on Heap however, you can specify the exact size in runtime. – HungryFoolish Dec 05 '22 at 10:21

0 Answers0