Search code examples
objectmemorymemory-managementoperating-systemprocedural-programming

How OOP languages differs from procedural languages in terms of memory utilization


I want to understand how OOP programming languages differs from procedural languages in terms of memory utilization. To be more specific, let's assume we are talking about Java and C as examples:

  1. Is it true that objects are automatically stored in heap while in procedural languages you have to explicitly define the heap usage such as in C malloc?
  2. If I write a program in C, OS will create a virtual page of this program including heap and stack spaces. If I don't use malloc in my code, this means my program does not utilize the heap allocated for it, is that correct?
  3. Since Stack is used to store local variables and function call addresses, what if a program ran out of Stack space, does OS extend the paging size of this program or it just uses the heap as an extension?

Solution

  • Is it true that objects are automatically stored in heap while in procedural languages you have to explicitly define the heap usage such as in C malloc?

    That depends upon the language. Some, such as Object Pascal, require all "objects" to be allocated on the heap. Others, such as C++, allow objects to exist in static, heap, or stack. There are advantages and disadvantages of both approaches.

    If I write a program in C, OS will create a virtual page of this program including heap and stack spaces. If I don't use malloc in my code, this means my program does not utilize the heap allocated for it, is that correct?

    Probably not. It is likely the run-time library will use the heap behind your back.

    Since Stack is used to store local variables and function call addresses, what if a program ran out of Stack space, does OS extend the paging size of this program or it just uses the heap as an extension?

    That depends upon the operating system. Generally, an OS will attempt to expand the stack if it can. t will not use the heap to extend the stack. Stacks are usually protected by an inaccessible page at either end (like the first page to catch null pointers). The likely outcome from running out of stack is some kind of access violation.