CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    Apr 2008
    Posts
    22

    pointers and memory ...pls clarify

    Hi All

    I will start with a very simple concept of pointers and memory that I have confusion about, before I move on to something related to MFC.

    assume the following piece of code:

    void func()
    {
    int *p = 10;
    ......
    ......
    }

    Here 'p' points to a memory location that contains the value 10; When the func() is exited, 'p' is popped oof the stack right? So the reference to the memory having the value 10 is gone. Now when is the memory released? Will it be any problem if some other piece of code tries to access this same memory location after 'p' goes out of scope?

    Please don't tell me anything about auto_ptr here. I want to know about the scope of pointers and memory they point to.


    Now lets come to the more complex involving threads (though I am going into multithreading).

    Say I have the following piece of code:

    HANDLE hThread ; //global var

    void funcCreateThread()
    {
    CWinThread *pthread = AfxBeginThread(ControllingFunc, .........);
    hThread = pthread->m_hThread;
    ......
    ......
    }

    AfxBeginThread creates a CWinThread object (on the process heap ? ) and returns a pointer to that memory which we are storing in pthread. I also store the handle to the created thread in a global var.

    When the function funcCreateThread() is exited, we lose the reference to this memory location but the memory for the object still persists right?


    Say towards the end of my application, I close the thread( by returning from its controlling function) and then call CloseHandle to release the handle as follows:

    WaitForSingleObject(hThread,10000)
    {
    .....
    }
    CloseHandle(hThread);
    hThread = NULL;

    Now what will happen to the CWinThread object and its memory location?

    Is it going to create a memory leak?


    The reason I am asking this is because my multithreaded application is causing EXCEPTION_ACCESS_VIOLATION and it also contains 3rd party DLL's and involves JNI. Is it possible that code in 3rd party DLL is trying to access this memory location which results in error?

    http://www.codeguru.com/forum/showthread.php?t=452661

  2. #2
    Join Date
    Aug 1999
    Location
    <Classified>
    Posts
    6,882

    Re: pointers and memory ...pls clarify

    About the first case, in your function 'func' the int *p is a function's local variable, meaning the variable p (which is a pointer) is created on function stack, now ideally one should allocate memory and then assign the address of it to this pointer so that it points to a valid memory location, but in your case the pointer p is not pointing to any valid memory location, it will have some garbage address value stored in it (as it is a local variable) and then that garbage address will be used to store the value '10', which is a memory write violation (by chance the garbage address might be a valid address value, thus it is not necessary for your code to show an error when run), but in ideal case when you have code like following,
    Code:
    void func()
    {
    int *p = new int; // required to allocate memory first before storing any value.
    *p = 10;
    ......
    ......
    }
    then the variable p is created on function stack and the new int is created on application heap, and then this new int's location (address) is assigned to p, so now when you assign 10 to this location is will be stored on heap, when the function exits, the memory allocated still stays there as you have not deleted it, so the value 10 will also stay there at that address, but as the variable p is local to function it will be cleared (because the function stack will be reverted back to previous Or caller function) you will effectively loose the address of the allocated memory, thus creating a memory leak of one int.
    Regards,
    Ramkrishna Pawar

  3. #3
    Join Date
    Feb 2000
    Location
    San Diego, CA
    Posts
    10,354

    Re: pointers and memory ...pls clarify

    Quote Originally Posted by Krishnaa
    but in your case the pointer p is not pointing to any valid memory location, it will have some garbage address value stored in it (as it is a local variable) and then that garbage address will be used to store the value '10', which is a memory write violation
    That is not really the case. int* p = (int*) 10 is perfectly valid and no access violation will happen. It is as good as int* p = new int; in that the variable p is assigned a value , which happens to be 10 in the first case, and some unknown value as returned by the new operator in the latter case. Whether it causes an access violation or not is determined by what is done with p later on. If you you try to access the value as *p, that is when it MIGHT generate an access violation depending on the contents of p if it is pointing to a memory area considered safe by the operating system.

    In any case, int* p causes cmpiler to reserve an area on the stack and when you go out of scope, it is automatically release in the stack unwind. No need to do anything explicit.

  4. #4
    Join Date
    Apr 2008
    Posts
    22

    Re: pointers and memory ...pls clarify

    Thanks

    But waht happens when I store a pointer to an object that I did not dynamically create, but was returned by some Windows API (e.g here AfxBeginThread) . Once the pointer to this CWinThread object is gone, what will happen to this object ?


    How can I delete such an object which I did not explicitly create (using malloc or new).

    Can you pls clarify the later part of the doubt that I had related to multithreading.

  5. #5
    Join Date
    Aug 2004
    Location
    Bucharest, Romania... sometimes
    Posts
    1,039

    Re: pointers and memory ...pls clarify

    Objects that you did not explicitely / implicitely create on the heap should not be deleted. Those created on the stack will be automatically destroyed when they go out of scope (including those created by copy-constructors). For other handles and resources retrieved by API, if needing to be freed, consult the documentation of those APIs. Also, APIs that allocate memory have matching APIs that deallocate such memory. Always use the matching version of the implementation that allocated something. These things are always documented thoroughly.
    Regards,
    Bogdan Apostol
    ESRI Developer Network

    Compilers demystified - Function pointers in Visual Basic 6.0
    Enables the use of function pointers in VB6 and shows how to embed native code in a VB application.

    Customize your R2H
    The unofficial board dedicated to ASUS R2H UMPC owners.

  6. #6
    Join Date
    Feb 2000
    Location
    San Diego, CA
    Posts
    10,354

    Re: pointers and memory ...pls clarify

    CWinThread has a m_bAutoDelete member which controls who is responsible for deleting the object. Please read up on that.

  7. #7
    Join Date
    Apr 2008
    Posts
    22

    Re: pointers and memory ...pls clarify

    Quote Originally Posted by kirants
    CWinThread has a m_bAutoDelete member which controls who is responsible for deleting the object. Please read up on that.

    I know that. In case we set m_bAutoDelete to false, it means that the CWinThread object won't be automatically deleted right?

    So is the following syntax correct.
    CWinThread *pthread = AfxBeginThread(...,CREATE_SUSPENDED.)
    pthread->m_bAutodelete = false;
    ....
    .....


    After closing the controlling function that runs as thread, I do this:
    CloseHandle(pthread->m_hThread);
    delete pthread;
    pthread = NULL;



    Do I need to call delete pthread ?

  8. #8
    Join Date
    Feb 2000
    Location
    San Diego, CA
    Posts
    10,354

    Re: pointers and memory ...pls clarify

    Yes, yes and yes to your 3 questions

  9. #9
    Join Date
    Apr 2008
    Posts
    22

    Re: pointers and memory ...pls clarify

    Thanks Kirant

    I posted the same ques in some another forum, and there too they said I need to use delete . But they also mentioned that I don't need to use CloseHandle(pthread->m_hThread) because the CWinThread's destructor automatically does it.


    Is it true? I did not find any documentation on CWinThread's destructor.

  10. #10
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: pointers and memory ...pls clarify

    Quote Originally Posted by krischk123
    Thanks Kirant

    I posted the same ques in some another forum, and there too they said I need to use delete . But they also mentioned that I don't need to use CloseHandle(pthread->m_hThread) because the CWinThread's destructor automatically does it.


    Is it true? I did not find any documentation on CWinThread's destructor.
    You can step into the MFC code and find out.

  11. #11
    Join Date
    Oct 2005
    Location
    Minnesota, U.S.A.
    Posts
    680

    Re: pointers and memory ...pls clarify

    Generally speaking, if the HANDLE is internal to the class, you don't need to worry about it. So, yes, you do NOT need to delete the handle if your CWinThread goes out of scope. BUT, you are allocating it as a pointer, so do you do have to delete the pointer returned (which will automatically take cake of the HANDLE).

    Code:
    CWinThread *g_pthread;
     
    void funcCreateThread()
    {
    	g_pthread = AfxBeginThread(ControllingFunc, .........);
    	// NO! Do not access this from CWinThread - Ever!
    	//	   Exception - change priorities
    	//hThread = pthread->m_hThread;
    	......
    	......
    }
     
    void funcCleanup()
    {
    	if( g_pthread )
    		delete g_pthread; // Make sure to clean up
    }
    If you do it with a CreateThread(), then you need to take care of the HANDLE since it is in your scope.

    -Erik
    Last edited by egawtry; May 29th, 2008 at 10:34 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured