-1

Say I have a pointer char* ptr allocated memory and another pointer char* arr = ptr

What happens to arr after ptr memory is deallocated.

Let the function be:

char* foo()
{
    char* ptr = new char [100];
    char* arr = ptr;
    delete [] ptr;
    return arr;
}

Can I use this returned value?

Will it cause any compile-time/Run-time error? Or any thing else.

Or what would happen if the function was

char* foo()
{
    char* ptr = new char [100];
    char* arr = ptr;
    delete [] arr;
    return ptr;
}

I guess there would be no change from previous output but would there be any change??

What would happen If I have a class

class Pointer
{
    public:
    char* ptr;
    Pointer()
    { 
        ptr= new char [100];
    }
    ~Pointer()
    {
        delete [] ptr;
    }
};

and function

 Pointer foo()
 {
     Pointer ptr;
     ptr.ptr[0]='l';
     return ptr;
 }

Wont destructor be called at the end of the function and create a dangling pointer Pointer::ptr ??

WARhead
  • 643
  • 5
  • 17
  • "Can I use this returned value??" You could but it's probably not smart, it could be a dangling pointer. Maybe if you're expecting a null return value, just return null or null `arr`. – George Dec 06 '16 at 16:36
  • arr points to garbage. don't return it. – AndyG Dec 06 '16 at 16:38
  • 1
    I think you're asking the wrong question. Nothing at all happens to `arr`. Or `ptr` for that matter. – juanchopanza Dec 06 '16 at 16:39
  • 1
    You can use it. But it's going to crash your program or worse, it doesn't and given you meaningless results. I think you need to first understand what is pointer and what is dynamic memory. You won't need to ask this question if you understand the basics – Yan Zhou Dec 06 '16 at 16:54
  • Same answer as http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794 – Cody Gray - on strike Dec 06 '16 at 16:59
  • About the edit: yes. The destructor will be called, and the pointer will be dangling. And there's no reason for you to reimplement the wheel. Getting smart pointers correct is somewhat hard - you'll need a very solid understanding of C++ to implement a smart pointer that works in all cases. Instead of your `Pointer`, you should use `std::shared_ptr`. Or `std::string` or `std::vector`. What I see you doing is approaching C++ like it was some C with classes where you had to roll everything on your own. Use what the language gives you. – Kuba hasn't forgotten Monica Dec 08 '16 at 14:17

3 Answers3

5

Can I use this returned value??

You can "use" it, but you can't dereference it. You could, for example, print the pointer value out (but not the pointed-to data!):

std::cout << (intptr_t)foo() << std::endl; // OK
std::cout << foo(); // WRONG: this dereferences the pointer!

So while the value can be "used", it's not really useful as a pointer to char anymore.

Or what would happen if the function was [...]

Both functions have the same meaning. On any decent compiler, you should expect both to yield identical machine code when compiled.

What happens to arr after ptr memory is deallocated?

Nothing happens to it: its value remains unchanged. But because the pointed-to object has been deallocated, it is now a dangling pointer. So you can't use it for anything: if you do, you'll get undefined behavior. Undefined behavior means that anything can happen. This includes: nothing happening (things "appear" to "work OK"), or getting your hard drive formatted.

The situation is the same is if you built a house on a lot. You give your friend Arr the GPS coordinates. But in the meantime you decided to move out. Yet your friend Arr still has the old coordinates. Now Arr decides to use them. There are several possible outcomes - and you have no control over which one happens. I'll list just a few:

  1. You moved out an hour ago. Everything is still the same. Arr stopped by, took a picture of your old home, and left.

    This corresponds to a case where due to a coincidence, the pointed-to memory still contains usable contents. You still have a bug, but coincidence hides it.

  2. You moved out, but the next day the city decided to raze the lot and build a big condo building on it and adjacent lots. Your friend comes in expecting a small house, sees a big condo high-rise and ends up completely stumped.

    This corresponds to a case where the memory gets reused followed by the dangling pointer dereference. Whether this leads to CPU raising an exception or not depends on what kind of an object lived there before.

  3. You moved out, but there was an earthquake and there's now a lake there. Your friend falls in and drowns.

    This corresponds to a case where a now-redundant chunk of virtual memory that used to be a part of the free store has been unmapped. You get a page fault.

    The memory manager runtime can deallocate the page that used to back the address space pointed to by your pointer. Recall that often a C++ program runs on top of a virtual memory machine. The address space seen by the program is the virtual address space. When there's no physical memory page backing a given virtual address space page, and no file or other backing for that page, any accesses to it will cause a page fault that propagates to userland and terminates the process if unhandled (as it is by default).

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
  • You can use it to point somewhere else, or to set it to `nullptr`. – juanchopanza Dec 06 '16 at 16:40
  • i understood reference 1&2 but what is 3 – WARhead Dec 06 '16 at 17:09
  • it can create a lot of fun with time travel too, certain platforms may handle the access violation by remapping a paged out version of the page that caused the violation. This may result in stale data happening without the program noticing. Long story short: undefined behavior is undefined and should be avoided at all costs. – Mgetz Dec 06 '16 at 17:22
  • @KubaOber Please revisit the question I have added some more doubts – WARhead Dec 08 '16 at 13:24
  • @WARhead Please ask a separate question. The question you had originally posed has been answered. You can't just make the questions grow as you accumulate "doubts". Think of what you're asking and ask another question. – Kuba hasn't forgotten Monica Dec 08 '16 at 14:15
0

From your code the arr would point to not allocated memory so if you tried to work with it it would contain absolutely random data.

Maroš Beťko
  • 2,181
  • 2
  • 16
  • 42
  • That's not really true, and the fact it's not true could be useful for something like embedded programming. – George Dec 06 '16 at 16:43
  • Embeded programming won't really bother someone asking so simple questions like what pointer points to after it's target is deallocated... – Maroš Beťko Dec 06 '16 at 16:46
0

I once worked on an embedded system, and, as luck sometimes happens, I had the debugger connected near the correct place at the correct time (with respect to the delete) when the system crashed. The code was C++, the debugger was gdb, vxWorks is an embedded system tool suite.

The code I inspected was in some ways similar to your question, essentially a dereference of the pointer occurred after the delete.

...
   char* ptr = new char [100];
   delete [] ptr;

   // more stuff that did not affect what ptr pointed to

   // about 5 to 9 lines later 
   char retVal = ptr[x];  // <<< invalid access crash
...

The crash indicated that ptr[x] is invalid.

That embedded system (vxWorks) had techniques to confirm that where ptr pointed was indeed no longer in context, unmapped from that task.

I would guess it unusual (because of performance), but the delete not only released the block from dynamic memory, it also released the block of memory from the thread memory space, making the address invalid, causing a bus error.

I do not know how to confirm the similar information in Linux.


What happens to arr after ptr memory is deallocated?

The auto variables are unaffected by the delete.


Can I use this returned value?

Behavior is undefined (i.e. UB), so you should want to avoid doing so.


Will it cause any compile-time/Run-time error? Or any thing else.

UB means any thing else can happen.

2785528
  • 5,438
  • 2
  • 18
  • 20