Check if i can do 'delete pointer'

Hello everyone!

1
2
3
4
5
6
7
8
9
void myfuncion()
{
    int *a = new int[10];
    int b[10];
    int *p = b;
    delete a
    delete p

}


I cant delete b and/or p but how can i check it if i can use delete or not?

i want to check if the pointer is pointing on function temp variable ( those what gets deleted after function ends ).

Thanks!
No , you can't check them.
But you can use a pointer wrapper like std::unique_ptr which would do the delete for you after the pointer goes out of scope.
Last edited on
You can never delete b because it was not created with new.

Just keep the pointer a and never change it in the function so that you can call delete on it at the end of the function.

Note that you should use delete[] when deleting arrays.

 
delete[] a;
Last edited on
@a k n
What do you mean by out of scope?
If the pointer will be lost then it will delete that data where pointer pointed?
( Im not sure how the pointer can get lost... )


@Peter87
But what if i do
delete a
then it would only free a[0] or what it would do?

I have always been using delete and never delete[] and i haven't noticed memory leaks.

I just tested it and checking ram usable in task manager and
delete and delete [] did the same thing.

at first i thought that delete [] was for **p but it didn't delete everything
still had to delete p[0] ... etc
The C++ standard says if you use delete without [] to delete an array the behavior is undefined, which means anything is allowed to happen. It might work in some cases, with some compilers but to be safe you should use the right version.
What do you mean by out of scope?

When a function exits, all the local symbols in the function become undefined. i.e. "go out of scope" of that function, since the scope of those symbols was local to that function.
If the pointer will be lost then it will delete that data where pointer pointed?

No. That is why you must explicitly delete any memory that you allocated using a regular pointer. However, by using a smart_ptr, the memory will be released by smart_ptr's destructor.
Im not sure how the pointer can get lost...

A pointer gets "lost", when the pointer variable goes out of scope. Once that happens, there is no longer any way to delete the memory that was pointed to. It's actually the memory that was pointed to that gets "lost", aka a memory leak. Memory can also get "lost" by reassigning a pointer.
1
2
3
  int *a = new int[10];
...
   a = new int[20];  // memory previously pointed to by a is now lost 


Last edited on
Topic archived. No new replies allowed.