-2

Is there a way to deallocate variables and/or objects created on the stack? I am specifically talking about the stack not the heap.

I do not want to debate whether this would be useful or good practise, I just need to know if it's possible.

I know it automatically deallocates when it goes out of scope. I want to deallocate it BEFORE it goes out of scope.

I am using C++.

fdh
  • 5,256
  • 13
  • 58
  • 101
  • 2
    What exactly do you mean by 'deallocate'? – smparkes Jan 26 '12 at 22:51
  • Not useful in practice for objects with trivial destructors, as the compiler does mojo with it under the covers. – Mooing Duck Jan 26 '12 at 22:51
  • @smparkes Free up the memory taken by that object or variable. – fdh Jan 26 '12 at 22:52
  • Why do you *need* to know if it's possible? Suppose for the sake of argument that it's possible. What would you do with that knowledge? – fredoverflow Jan 26 '12 at 22:52
  • @MooingDuck I do not care about usefulness at this moment, I just need to know if its possible in C++. – fdh Jan 26 '12 at 22:53
  • @FredOverflow Sorry, but I am not allowed to share the purpose of it. I just need to know how to do it. – fdh Jan 26 '12 at 22:53
  • Then, no, you cannot explicitly free stack allocated memory. It's completely managed by the compiler based on declarations and control flow. – smparkes Jan 26 '12 at 22:54
  • Sounds dangerous, as it would still be in scope, but no longer on the stack. Not sure how the compiler would like this. – Nic Foster Jan 26 '12 at 22:54
  • 8
    It's impossible. Now you know, and you can get on with your life. – fredoverflow Jan 26 '12 at 22:55
  • 3
    Sounds like a case of [the XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – R. Martinho Fernandes Jan 26 '12 at 22:59
  • 1
    Why was this question downvoted? Its a legitimate question and follows all the rules on this site. – fdh Jan 26 '12 at 23:00
  • @fdh Well you're not exactly giving much complementary information that's being asked... Typically "*what for ?*" Then we can maybe think of another way, or at least have some more insight into your question. – Cimbali Jan 15 '15 at 11:23

6 Answers6

10
{
  int a;
} // 'a' "deallocated" here

You can't get rid of a before the end of the enclosing scope.

Xeo
  • 129,499
  • 52
  • 291
  • 397
5

Every time you return from a function, any memory allocated on the stack by that function is deallocated. If you need to reduce the scope of a variable for some reason, you can just make a new smaller scope by creating a block with {}.

void function(void)
{
   int x;
   {
     int y;
   } // scope of y ends
} // scope of x ends
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

You cannot prematurely end the lifetime of an "automatic" object, but you can end the lifetime of a dynamic object at any time. A dynamic object can be created on the stack just like an automatic variable, but it's a hair trickier.

#include <new>
#include <string>
int main() {
    typedef std::aligned_storage<sizeof(std::string)> stringbuffer;
    stringbuffer buff;
    std::string& str =*new(buff)std::string("banana"); //str alive on stack
    std::cout << str;       
    str.~std::string(); // str is destroyed. DO NOT FORGET
    std::cout << '\n';
}

This is error prone, so of course, boost has code for this.

int main() {
    boost::optional<std::string> str;
    str = "banana"; //str is alive on the stack
    std::cout << str;       
    str = boost::none; //str is destroyed.  Ok to forget
    std::cout << '\n';
}

Both of these avoid the potential UB of FredOverflow's answer, since if an exception is thrown while the object is not alive, the destructor is not automatically called on the dead object.

Azza notes that this does not deallocate the space, it merely destructs. It is impossible to deallocate the space early.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
2

Stack variables are deallocated when they go out of scope. That's it.

Stephen
  • 3,515
  • 5
  • 27
  • 33
  • I know, I need to deallocate it BEFORE it goes out of scope. – fdh Jan 26 '12 at 22:54
  • @Farhad - why? That's the only conceptual thing that makes sense. If you need to, you can create a smaller scope for your variable by creating a new block with `{}`. – Carl Norum Jan 26 '12 at 22:54
  • Not true. `void foo(void) { int a; bar(); }` when `bar` is executed `a` is out of scope but is not deallocated. – ouah Jan 26 '12 at 22:58
  • @Farhad: I guess what I was trying to say was, "No, you can't." – Stephen Jan 26 '12 at 23:06
  • @MooingDuck in that case try to print the value of `a` in `bar` and see if you get a compilation error. – ouah Jan 26 '12 at 23:17
  • @MooingDuck the scope is the region of the program where an identifier is visible. – ouah Jan 26 '12 at 23:21
2

The question is meaningless. Generally, stack for thread is allocated (memory reserved and partially committed) on process heap when thread is created. And dealocated when thread (normally) exits . It has a fixed maximum size (reserved memory) during run-time and "grows" by committing more memory from reserved pool. There is no actual memory allocation happens when function call uses stack - the stack space function uses (for its local variables) is a region of pre-allocated and committed memory. You cannot de-allocate it.

Imagine, you allocated 100 bytes on heap at address addr, pass pointer to addr+0x40 and size 0x10 to function for it to use internally. Function can create some variables (objects) at this address, total size no more than 16 bytes, using, say, placement new. It can (and, generally, should) destroy objects by calling destructors explicitly. But it has no business deallocating any memory - pointer passed to it does not even point to the beginning of allocated region... And that's, very simplified, how stack works - function gets portion of pre-allocated memory for its local variables, it calls constructors at this memory, then upon exit it calls destructors. But it does not allocate or deallocate any stack space. Attempt to do it will cause access violation (segmentation fault).

lapk
  • 3,838
  • 1
  • 23
  • 28
1

No, it's not possible to deallocate a stack variable before it goes out of scope in portable C++.

It would be possible to do something retarded and non-portable with inline assembly like this (example works only with x86, only with Visual Studio):

int* ptr;

__asm {
    sub esp, sizeof(int)           // allocate variable
    mov [esp + sizeof(int)], esp   // move its address into ptr
}

*ptr = 4;                          // assign 4 to the variable
cout << *ptr << endl;              // print variable

__asm {
    add esp, sizeof(int)           // deallocate variable
}

But don't, there are too many problems to name.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249