Is the stack pre-allocated in a process?

Issue

Well, my question is as follows, I saw somewhere that a linux process allocates 8 MiB on the stack to be used, if I have a C program for example, that I only allocate two variables on the stack, it is right to say that I allocated or is it better to say that I just reused that space? Since a process allocates 8 MiB on the stack it does not depend on the size that I am going to use in my program, as long as it does not exceed my stack, that is, whichever term is appropriate, I will allocate a data on the stack or I will reuse a data that has already been allocated by a linux process?

#include <stdio.h>

void f() {
   int x = 5;
   printf("Value = %d End = %p\n", x, &x);
}

void g() {
   int y = 10;
   printf("Value = %d End = %p\n", y, &y);
}

int main(){

  f();
  g();
  return 0;
}

See that the addresses will be the same, because I reused the size that had already been allocated, the same wouldn’t happen with malloc, summarizing the term Allocated right data in the Stack isn’t very correct?

Solution

Is the stack pre-allocated in a process?

On a stack-based architecture, a process will have stack space available to it from the beginning of its execution. That could be described as "pre-allocated". However, do note that in some contexts, it may be possible for a process’s stack to be extended during the lifetime of the process. Perhaps that changes how you would view it?

In any case, that has little to do with whether the process of assigning storage space for automatic variables should be described as "allocation". Although it has technical implications, it is of little account linguistically that such space may be carved out of the stack, as opposed to out of some other area of memory controlled by the process. The lifetimes of such objects do obey different rules than the lifetimes of mallocated objects, but so what?

if I have a C program for example, that I only allocate two variables on the stack, it is right to say that I allocated or is it better to say that I just reused that space?

People are likely to understand you just fine either way. Although I’m sure there are some who would quibble over whether "allocate" is technically correct for automatic variables, it is nevertheless widely used for them. If you are conversing with people, as opposed to writing technical documentation to which the distinction is important, then I would not hesitate to use "allocate" to describe assigning storage space to automatic variables.

Answered By – John Bollinger

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published