Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've been calling heap pointers now for as long as I can remember, which in turn has caused me to think about their implications while writing and what I realised was I have no knowledge on how or even if it is possible to clear a stack variable declared within main() from memory once it has been allocated.

Clearly I can just use a struct and destructor or similar, which I would but lets for say I wanted to remove an array that was on the stack declared in main() is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
178 views
Welcome To Ask or Share your Answers For Others

1 Answer

I wanted to remove an array that was on the stack declared in main() is it possible?

Yes.

In main() (and most anywhere you use an automatic variable), you can trigger a dtor by closing the containing scope.

Example:

int main(int argc, char* argv[])
{
   int retVal = 0;
   int arr[10];
   T610_t  t610;
   retVal = t610.exec(argc, argv);
   // ...
   // ...  // t610 exists to end of main() scope.
   // ...  // arr[10] exists to end of main() scope
   return retVal;
}

Instance t610 (of the user defined T610_t type) lasts the life-time of the program, even when not used after the exec() returns retVal;


In contrast:

int main(int argc, char* argv[])
{
   int retVal = 0;
   {
      int arr[10];
      T610_t  t610;
      retVal = t610.exec(argc, argv);
   }
   // ...   // no t610 instance exists, and arr[] is no longer accessible
   // ...
   // ...
   // ...
   return retVal;
}

The dtor of instance t610 is called at the close-brace after exec() returns retVal. arr[10] also no longer exists.

All the lines after the close brace do not have access to T610_t, nor arr[10], and any automatic memory grabbed in the 'small scope' is 'released' for re-use. (for instance, another T610_t instance...)

Any 'clearing' of the space used by T610_t is dependent on what the dtor does and what you mean by clearing. Thus, for instance, an array data attribute of T610_t can be filled with 0's (to 'clear' it), and the dtor also releases the memory for re-use. Remember, do no delete when you did no 'new'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...