Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. detect invalid reference

detect invalid reference

Scheduled Pinned Locked Moved C / C++ / MFC
questiongraphics
12 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T toxcct

    best practices teach to NULL a pointer you just delete...

    delete testVector;
    testVector = NULL;

    what i suspect you was to expecting the last cout to print 0x00000000. but delete frees the memory pointed to by the pointer, nothing much.


    [VisualCalc][Flags Beginner's Guide] | [Forums Guidelines][My Best Advice]

    M Offline
    M Offline
    Mr Brainley
    wrote on last edited by
    #3

    That is not the problem. I don't even reference the pointer. I reference an element of the vector that has been destroyed. I could leave the delete on the vector and it would still print nonsense. The reference to the integer stored in the vector has become invalid. I have this problem because i need to implement a wrapper for a map on wich multiple threads can operate concurrently, inserting, reading and deleting. Now one thread could delete an element another thread is currently working on. Since the objects are managed by the map itself i cannot find out when that happened.

    T D 2 Replies Last reply
    0
    • M Mr Brainley

      That is not the problem. I don't even reference the pointer. I reference an element of the vector that has been destroyed. I could leave the delete on the vector and it would still print nonsense. The reference to the integer stored in the vector has become invalid. I have this problem because i need to implement a wrapper for a map on wich multiple threads can operate concurrently, inserting, reading and deleting. Now one thread could delete an element another thread is currently working on. Since the objects are managed by the map itself i cannot find out when that happened.

      T Offline
      T Offline
      toxcct
      wrote on last edited by
      #4

      what do you mean by "print non-sense" ? what do you expect ? [edit] oh, my bad, i read your post incorrectly (i read that you were printing out the address in the testVector pointer). AFAIK, a reference cannot be changed of address, so by clearing the vector, then deleting it, you invalidate the reference. the only way you have to know the reference may be invalid is not writing such code. i don't think we can know otherwise BTW, it seems that you need some synchronizing code around your vector... one should not read it until another thread finished to modify it, and such references being temporary shouldn't be stored [/edit]


      [VisualCalc][Flags Beginner's Guide] | [Forums Guidelines][My Best Advice]

      M 1 Reply Last reply
      0
      • M Mr Brainley

        That is not the problem. I don't even reference the pointer. I reference an element of the vector that has been destroyed. I could leave the delete on the vector and it would still print nonsense. The reference to the integer stored in the vector has become invalid. I have this problem because i need to implement a wrapper for a map on wich multiple threads can operate concurrently, inserting, reading and deleting. Now one thread could delete an element another thread is currently working on. Since the objects are managed by the map itself i cannot find out when that happened.

        D Offline
        D Offline
        David Crow
        wrote on last edited by
        #5

        Mr.Brainley wrote:

        I reference an element of the vector that has been destroyed.

        This would be impossible if you had assigned NULL to the pointer after deleting it. It's a two-step process. Assign NULL to the pointer after deleting it, and check if the pointer is equal to NULL before referencing it.


        "Approved Workmen Are Not Ashamed" - 2 Timothy 2:15

        "Judge not by the eye but by the heart." - Native American Proverb

        1 Reply Last reply
        0
        • T toxcct

          what do you mean by "print non-sense" ? what do you expect ? [edit] oh, my bad, i read your post incorrectly (i read that you were printing out the address in the testVector pointer). AFAIK, a reference cannot be changed of address, so by clearing the vector, then deleting it, you invalidate the reference. the only way you have to know the reference may be invalid is not writing such code. i don't think we can know otherwise BTW, it seems that you need some synchronizing code around your vector... one should not read it until another thread finished to modify it, and such references being temporary shouldn't be stored [/edit]


          [VisualCalc][Flags Beginner's Guide] | [Forums Guidelines][My Best Advice]

          M Offline
          M Offline
          Mr Brainley
          wrote on last edited by
          #6

          Synchronization is of course neccessary (bad seplling ?!), but i want to keep it minimal, since too much synchronization can make a multithreaded application almost sequential, this voiding the advantage of multithreading. It is also correct that the reference should not be stored, but experience tells us, that users always do whatever it takes to crash a program, or the library in that case. So i try to keep my code bulletproof. My approach now is to write a wrapper-class that behaves like a reference, but checks on every access weather the elemennt/vector actually still exists. I'm not sure though if that is the smartest way to do it, it seems like a waste of resources.

          T 1 Reply Last reply
          0
          • M Mr Brainley

            Synchronization is of course neccessary (bad seplling ?!), but i want to keep it minimal, since too much synchronization can make a multithreaded application almost sequential, this voiding the advantage of multithreading. It is also correct that the reference should not be stored, but experience tells us, that users always do whatever it takes to crash a program, or the library in that case. So i try to keep my code bulletproof. My approach now is to write a wrapper-class that behaves like a reference, but checks on every access weather the elemennt/vector actually still exists. I'm not sure though if that is the smartest way to do it, it seems like a waste of resources.

            T Offline
            T Offline
            toxcct
            wrote on last edited by
            #7

            Mr.Brainley wrote:

            but i want to keep it minimal

            don't keep it "minimal", keep it efficient. if you have too much synchronization, then there may have a design problem. for your vector, the need of the mutex is pretty neat...


            [VisualCalc][Flags Beginner's Guide] | [Forums Guidelines][My Best Advice]

            1 Reply Last reply
            0
            • M Mr Brainley

              Consider the following code :

              vector    \*testVector = new vector();
              
              testVector->push\_back(1);
              
              int &testRef   = (\*testVector)\[0\];
              cout << testRef << endl;
              
              //  completeley destroy the vector and everything in it
              testVector->clear();
              delete testVector;
              
              //  now access the invalid reference
              cout << testRef << endl;
              //  works, but prints nonsense
              

              How can i detect that the reference has become invalid ?

              M Offline
              M Offline
              Michael Dunn
              wrote on last edited by
              #8

              A try/catch around the dereference would do it, but it's cumbersome to have many of those throughout the app. In C++, it's your responsibility to not do that in the first place. :)

              --Mike-- Visual C++ MVP :cool: LINKS~! Ericahist | PimpFish | CP SearchBar v3.0 | C++ Forum FAQ Ford, what's this fish doing in my ear?

              S 1 Reply Last reply
              0
              • M Mr Brainley

                Consider the following code :

                vector    \*testVector = new vector();
                
                testVector->push\_back(1);
                
                int &testRef   = (\*testVector)\[0\];
                cout << testRef << endl;
                
                //  completeley destroy the vector and everything in it
                testVector->clear();
                delete testVector;
                
                //  now access the invalid reference
                cout << testRef << endl;
                //  works, but prints nonsense
                

                How can i detect that the reference has become invalid ?

                J Offline
                J Offline
                John R Shaw
                wrote on last edited by
                #9

                Mr.Brainley wrote:

                How can i detect that the reference has become invalid ?

                You can not; a reference just refers to a memory block that is expected to contain data of a given type (the referenced data type). It is up to you, the programmer, to insure that the memory block is valid, as the language does not provide that for you. If there is a chance that the memory block will become invalid without you knowing it, bad design, then you could try using one of Microsoft’s “IsBad…” functions to check the address referred to by the reference: IsBadWritePtr(&testRef,sizeof(int)). This method, of course, may not work if some other piece of code has allocated that same memory block between the time you freed it and the time you checked the address pointer; which will lead to very hard to find bugs. Another thing I would like to point out is that just adding another item to the ‘vector’ can cause your reference to become invalid if the ‘vector’ had to reallocate memory in order to expand the memory block size. Basically, any reference, of the type you provided, should be temporary and only exist in local scope. It should not be ‘static’ or ‘global’, unless the memory it refers to is not released until the application exits.

                INTP "Program testing can be used to show the presence of bugs, but never to show their absence."Edsger Dijkstra

                1 Reply Last reply
                0
                • M Mr Brainley

                  Consider the following code :

                  vector    \*testVector = new vector();
                  
                  testVector->push\_back(1);
                  
                  int &testRef   = (\*testVector)\[0\];
                  cout << testRef << endl;
                  
                  //  completeley destroy the vector and everything in it
                  testVector->clear();
                  delete testVector;
                  
                  //  now access the invalid reference
                  cout << testRef << endl;
                  //  works, but prints nonsense
                  

                  How can i detect that the reference has become invalid ?

                  S Offline
                  S Offline
                  Stephen Hewitt
                  wrote on last edited by
                  #10

                  The best solution would be not to get in this situation. There are other solutions however. For example you could construct a container based on a std::vector that uses something like Boost's Shared Container Iterator[^] and use iterators instread of usig ponters. Other smart pointer based techniques are also possible. A std::vector as it stands is not designed for this usage pattern (and doesn't pay the price that implementing it incurs).

                  Steve

                  1 Reply Last reply
                  0
                  • M Michael Dunn

                    A try/catch around the dereference would do it, but it's cumbersome to have many of those throughout the app. In C++, it's your responsibility to not do that in the first place. :)

                    --Mike-- Visual C++ MVP :cool: LINKS~! Ericahist | PimpFish | CP SearchBar v3.0 | C++ Forum FAQ Ford, what's this fish doing in my ear?

                    S Offline
                    S Offline
                    Stephen Hewitt
                    wrote on last edited by
                    #11

                    Michael Dunn wrote:

                    A try/catch around the dereference would do it, but it's cumbersome to have many of those throughout the app. In C++, it's your responsibility to not do that in the first place.

                    I don't think it would (do it). This approach is dangerous. The memory manager could have reused the address that used to contain the vector's contents after the vector has been destroyed. This technique can not be relied upon.

                    Steve

                    1 Reply Last reply
                    0
                    • M Mr Brainley

                      Consider the following code :

                      vector    \*testVector = new vector();
                      
                      testVector->push\_back(1);
                      
                      int &testRef   = (\*testVector)\[0\];
                      cout << testRef << endl;
                      
                      //  completeley destroy the vector and everything in it
                      testVector->clear();
                      delete testVector;
                      
                      //  now access the invalid reference
                      cout << testRef << endl;
                      //  works, but prints nonsense
                      

                      How can i detect that the reference has become invalid ?

                      N Offline
                      N Offline
                      Nemanja Trifunovic
                      wrote on last edited by
                      #12

                      Mr.Brainley wrote:

                      How can i detect that the reference has become invalid ?

                      You can't. BTW, vector objects are not meant to be created on the heap.


                      Programming Blog utf8-cpp

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups