0

C++ do stack memory allocation/deallocation defragement memory. when i declare local memory variables, they are allocated and deallocated, does it makes memory fragemented?

this can be very important from memory point of view

how much memory is availabe for stack? can I allocate

 char sam[999999999999999];
osgx
  • 90,338
  • 53
  • 357
  • 513
Vijay
  • 2,021
  • 4
  • 24
  • 33
  • See: [here](http://stackoverflow.com/questions/216259/is-there-a-max-array-length-limit-in-c/216731#216731) for limits on stack size. – Martin York Mar 29 '11 at 17:00

4 Answers4

3

No, memory is not fragmented. How much memory you can allocate on stack is implementation-defined, usually something around 1 megabyte.

sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • Memory IS fragmented. Especially when a lot of malloc/free is used. The layout of complex data structures goes worse on fragmented memory (more pages is used; memory locality is lower; TLB pressure is higher). Physical memory can be fragmented (no single continuous region may be available to huge page allocator). Virtual address space may be fragmented (no mmap of huge size will success even enough memory is free in discontinuous manner). – osgx Aug 31 '11 at 21:33
  • @osgx: Stack allocation doesn't use `malloc()`/`free()`. – sharptooth Sep 01 '11 at 05:51
  • But it uses physical/virtual mapping. And pages for stack may be allocated in different order. And ... I suggest you to edit your answer and say "Stack memory is not fragmented". – osgx Sep 01 '11 at 10:15
2

Allocating builtins on the stack shouldn't result in fragmentation. However if you allocate something like string on the stack, while the stack itself won't get fragmented the string allocates memory on the heap which could wind up fragmented.

Generally the stack is extremely small compared to the heap - something like 1-64MB depending on your platform.

Mark B
  • 95,107
  • 10
  • 109
  • 188
1

how much memory is available for stack?

It depends.


It depends on the compiler and it depends on the parameters you launch your binary with (since compilers may decide to defer the definition of the stack size to the runtime). It also depends on the OS and the available resources.

One point of interest, gcc is working on SplitStacks. A number of languages already offer this (Go for example), the idea is that the stack can then grow on demand. At this point, the limit becomes: how much can the OS allocate in one go ?

I haven't experimented it yet... don't even know if this is fully implemented.

Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

By doing allocation and deallocation on stack memory will not be frgameneted as how much memory is required for a stack variable is known at the compile time itself. Regarding the maximum amount of memory you can allocate on stack depends on the compiler. By default, for VS compilers its 1 MB and can be chnaged through compiler options.

Asha
  • 11,002
  • 6
  • 44
  • 66