Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 585007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T14:57:28+00:00 2026-05-13T14:57:28+00:00

I have a function which makes use of memory on the heap and it

  • 0

I have a function which makes use of memory on the heap and it will go badly wrong if it is called before another instance of the same function has completed.
How can I prevent this from happening at compile time?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T14:57:28+00:00Added an answer on May 13, 2026 at 2:57 pm

    Detecting recursion with any amount determinism of at compile-time is going to be quite difficult. Some static code analysis tools might be able to do it, but even then you can get in to run-time scenarios involving threads that code analyzers won’t be able to detect.

    You need to detect recursion at run-time. Fundamentally, it’s very simple to do this:

    bool MyFnSimple()
    {
        static bool entered = false;
        if( entered )
        {
            cout << "Re-entered function!" << endl;
            return false;
        }
        entered = true;
    
        // ...
    
        entered = false;
        return true;
    }
    

    The biggest problem with this, of course, is it is not thread safe. There are a couple of ways to make it thread safe, the simplest being to use a critical section and block the second entry until the first has left. Windows code (no error handling included):

    bool MyFnCritSecBlocking()
    {
        static HANDLE cs = CreateMutex(0, 0, 0);
        WaitForSingleObject(cs, INFINITE);
        // ... do stuff
        ReleaseMutex(cs);
        return true;
    }
    

    If you want the function to return an error when a function has been reentered, you can first test the critsec before grabbing it:

    bool MyFnCritSecNonBlocking()
    {
        static HANDLE cs = CreateMutex(0, 0, 0);
        DWORD ret = WaitForSingleObject(cs, 0);
        if( WAIT_TIMEOUT == ret )
            return false;   // someone's already in here
        // ... do stuff
        ReleaseMutex(cs);
        return true;
    }
    

    There are probably an infinite ways to skin this cat other than the use of static bools and critsecs. One that comes to mind is a combination of testing a local value with one of the Interlocked functions in Windows:

    bool MyFnInterlocked()
    {
        static LONG volatile entered = 0;
        LONG ret = InterlockedCompareExchange(&entered, 1, 0);
        if( ret == 1 )
            return false;   // someone's already in here
        // ... do stuff
        InterlockedExchange(&entered, 0);
        return false;
    }
    

    And, of course, you have to think about exception safety and deadlocks. You don’t want a failure in your function to leave it un-enterable by any code. You can wrap any of the constructs above in RAII in order to ensure the release of a lock when an exception or early exit occurs in your function.

    UPDATE:

    After readong comments I realized I could have included code that illustrates how to implement an RAII solution, since any real code you write is going to use RAII to handle errors. Here is a simple RAII implementation that also illustrates what happens at runtime when things go wrong:

    #include <windows.h>
    #include <cstdlib>
    #include <stdexcept>
    #include <iostream>
    
    class CritSecLock
    {
    public:
        CritSecLock(HANDLE cs) : cs_(cs)
        {
            DWORD ret = WaitForSingleObject(cs_, INFINITE);
            if( ret != WAIT_OBJECT_0 ) 
                throw std::runtime_error("Unable To Acquire Mutex");
            std::cout << "Locked" << std::endl;
        }
        ~CritSecLock()
        {
            std::cout << "Unlocked" << std::endl;
            ReleaseMutex(cs_);
        }
    private:
        HANDLE cs_;
    };
    
    bool MyFnPrimitiveRAII()
    {
        static HANDLE cs = CreateMutex(0, 0, 0);
        try
        {
            CritSecLock lock(cs);
            // ... do stuff
            throw std::runtime_error("kerflewy!");
            return true;
        }
        catch(...)
        {
            // something went wrong 
            // either with the CritSecLock instantiation
            // or with the 'do stuff' code
            std::cout << "ErrorDetected" << std::endl;
            return false;
        }
    }
    
    int main()
    {
        MyFnPrimitiveRAII();
        return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

hi i have function which is called by tinker listbox so i cannot return
I have to use a function from a shared library which leaks some small
I have a function in which I make use of a local array. I
Say, i have a function which returns a reference and i want to make
I am having a classes which have function to make random text and captcha
I have to make a function which concatenates two strings but I have to
Can I´m asking for advice. I have function which should return javascript object function
I have a function which looks something like this, it returns a noncopyable class
I have a function which I have to loop it a few times but
I have a function which takes two arguments, the ID of an item (wine)

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.