Serge Roussak
Serge Roussak

Reputation: 1807

Is result of allocation in heap interdependent to result of allocation in stack?

Let's consider this code:

static const size_t DATA_SIZE = 100000;

void log_msg(const char* msg)
{
  char msg_buffer[DATA_SIZE];
  // Do something...
}

int main()
{
  // Do something heap-memory consuming...

  unsigned char buffer = new unsigned char[DATA_SIZE];
  if(!buffer)
  {
    log_msg("Insufficient memory!");
    return 1;
  }

  // Go ahead...

  delete[] buffer;

  return 0;
}

Now, let's imagine that at the moment of allocation memory in the heap for the buffer there is no free space AND, at the same time, there is enough free space in the stack.

My question is pretty simple: will allocation in the stack for the msg_buffer be ALWAYS erroneous if allocation for the buffer in the heap is erroneous?

As far as I know, the stack is allocated for each thread and the heap -- for process. So, is there any guaranty that result of memory allocation in the stack will not correlate to result of memory allocation in the heap? Of course, I don't consider the stack overflow in itself. In other words, is the memory which reserved for the stack actually reserved for it fully? Or could there be situations when for some reason during program execution this reservation can be shrunk?

If there are no platform-independent assertions concerning this then I could know whether there are ones for the case of Linux for x86 architecture.

Upvotes: 1

Views: 46

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148880

This is explicitly implementation dependent. By the way, the mere notion of stack and heap do not exist in standard even if they are common in real world implementation.

I can remember the good old MS/DOS systems where the allocation types could depend on the memory model. Some compilers used one single segment (SS) in small and medium models for both the stack and the heap, the stack growing from one end and the heap from the other, but used allocation from the memory above the program (so independent of stack) for compact and large models.

In the former case, if stack allocation was not possible, heap allocation was not either, but in the latter heap and stack allocation could succeed or fail independantly.

In modern OS using virtual memory like Linux, it is common to have a fixed size stack, and ask the OS for new free blocks for the heap. In that case, stack and heap allocation can succeed or fail independently

Upvotes: 1

Related Questions