Copying a pointer and then calling delete - c++

If I copy a pointer and then ask for the pointed to allocation to be deleted is it valid C++, or is it undefined? I am not finding a satisfactory answer from google. Thanks.
char* orig = new char[100];
char* copy = orig;
delete[] copy;

It's perfectly valid. You are deallocating the array that you allocated on the first line.
Note that copying the pointer doesn't copy the allocated array. So you allocate one array and then you deallocate one array, leaving you with no arrays remaining.

but don't forget that orig points to the same memory, so when you delete[] copy the orig pointer becomes unusable as well.... oh sorry Joseph has already said this.

when you delete the 2nd pointer it will delete the allocated array but the first pointer is pointing towards the same memory location therefore it will become the dangling pointer.

Related

Confusion about delete operator in C++

This looks simple question but my friend debated with me that below program invokes UB. But I think he is incorrect.
Consider following program:
#include <iostream>
int main()
{
int* p=new int[3]();
int* q=p;
for(int i=0;i<3;i++)
std::cout<<q[i]<<' ';
delete[] q;
std::cout<<'\n';
}
Is this program's behavior well defined? What happen if I write delete[] p; instead of delete[] q; ? Is it valid?
Yes the program is well defined. First you create a pointer assigned to newly allocated memory.
int* p=new int[3]();
Then you create another pointer pointing to that memory
int* q=p;
You then use that pointer to assign data into that memory. After that you delete memory which is pointer to q which is the same as p which is okay. The program returns and all is well
delete doesn't care about what variable you use. What is important is that the memory that the pointer points to was created with new and that you only call delete once on the memory.
The pointer returned by the new[] operator is not the start of the allocated memory but rather points to the first object (or the object at index 0). Now, based on the compiler you're using, the run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the memory location pointed by p.
According to this blog, the deletion of a vector performs this operation in reverse:
When you do "delete[] p", you are saying, "p points to a bunch of
objects, but I'm not telling you how many." In this case, the compiler
needs to generate extra code to keep track of how many it needs to
destruct. This extra information is kept in a "secret place" when the
vector is allocated with "new[]".
Since doing int *q = p essentially points to the same array's 0th object, it is equivalent to call delete[] q and delete[] p.
Operator delete can be applied ONLY to memory (i.e. address) that was allocated with operator new. If you allocate once you should free (detele) also once, does not metter which pointer (variable storing address) is used, so your code is valid.
But, remember, after you delete[] q neither q nor p DO NOT have to be used. The best way is assigne NULL to both pointers.
No UB. It will work fine. Not much to add here.

Reusing a pointer to array after deletion

This the code:
char * asd = new char[10];
delete [] asd;
asd = new char[20];
Questions:
Doesn't the delete operation on pointers deletes the allocated memory being pointed to by the pointer?
is alright to reuse pointers after performing delete it on?
Doesn't the delete operation on pointers deletes the allocated memory
being pointed to by the pointer?
Yes.
is alright to reuse pointers after performing delete it on?
Yes, that's fine, as long as you set the pointer to the address of a different, valid object, which is what you are doing with your second invocation of new[].
Note that your question title "Reusing an array after deletion", is irrelevant to your question. You are not reusing an array that has been deleted, you are just reusing a pointer that used to point to an array which is now deleted.

Delete array from an offset

Lets say I allocate an array of ints
int test[] = new int[100];
I take a pointer to somewhere in the middle
int *temp = &test[50];
Then I call delete[] on the temp
delete[] temp
How will the compiler know the size of elements to delete in this case?
It won't (or will, I don't know). You're invoking undefined behavior. You're only allowed to call delete[] on a pointer allocated with new[].
For example, I get a crash in MSVS.
You have to pass the same memory location which was returned by new[], passing anything else is undefined behavior.
You cannot do that. A compiler has to keep track of the size of memory that it allocates. The standard does not say how it must to this. Some compilers store the size of the allocated memory just before the returned address. In such cases what you're doing can lead to undefined behavior.
The answer is no.
Because delete operator need to locate the location of the memory block and it's size, which is mostly ahead the first member of the allocated array.
you should have a look at the "Inside c++ object model"

delete a variable out of scope

int* func()
{
int* i=new int[1];
//do something
return i;
}
void funcc()
{
int* tmp=func();
//delete allocated memory after use
delete tmp;
}
should delete working as described in the second function be a correct use ?
I think I didn't allocate memory to it by new ? new was used in the first, to be sure.
It should be delete [] tmp; because you're doing array new, but otherwise, it's correct.
As others have stated, you should use delete[] to delete arrays, not delete.
But, if you're asking whether it's okay to delete tmp because the memory it points to wasn't allocated with new, then your premise is incorrect.
It was allocated with new. The address of the memory that you allocate within the function for i is passed back to be stored in tmp, so it does point to memory that was allocated by new.
You're correct that i itself is out of scope at that point but memory allocated by new survives the scope change on exit from the function. And, since you're storing its location into tmp, you still have access to it.
Hence the deletion (once you make it an array deletion with []) is quite valid.
This is Undefined Behaviourâ„¢. You can only use delete if you used new. If you used new[], you MUST delete[] it. More than that, this is hideously unsafe code- you need a smart pointer.
No. new T[] should match delete []t. And new T should match delete t. Otherwise, your code would invoke undefined bevavior.
And it doesn't matter if you do delete []tmp outside the function. Its okay to do so. All that you need to keep in mind that the form of delete.
My spidey-senses tell me that you're wondering whether the dynamically-allocated int that you create in func is the same one that you attempt to delete in funcc.
The answer is: yes. Although you don't use strictly the same pointer variable, both pointers point to the same object.
However, please remember to use delete[] (with the []) when you used new[] (with the []). Your code is broken until you fix this.
Also, try to avoid newing in one place and deleteing in another. Perhaps consider a std::vector instead, which is far less error-prone.

What does deleting a pointer mean?

Is deleting a pointer same as freeing a pointer (that allocates the memory)?
Deleting a pointer (or deleting what it points to, alternatively) means
delete p;
delete[] p; // for arrays
p was allocated prior to that statement like
p = new type;
It may also refer to using other ways of dynamic memory management, like free
free(p);
which was previously allocated using malloc or calloc
p = malloc(size);
The latter is more often referred to as "freeing", while the former is more often called "deleting". delete is used for classes with a destructor since delete will call the destructor in addition to freeing the memory. free (and malloc, calloc etc) is used for basic types, but in C++ new and delete can be used for them likewise, so there isn't much reason to use malloc in C++, except for compatibility reasons.
You can't "delete" a pointer variable
Sure you can ;-)
int** p = new int*(new int(42));
delete *p;
delete p; // <--- deletes a pointer
But seriously, delete should really be called delete_what_the_following_pointer_points_to.
Yes, delete is used to deallocate memory and call the destructor for the object involved.
It's common pratice to set pointer to NULL after deleting it to avoid having invalid pointers around:
Object *o = new Object();
// use object
delete o; // call o->~Object(), then releases memory
o = NULL;
When new and delete are used with standard C types in C++ source they behave like malloc and free.
You can't "delete" a pointer variable, only set their value to NULL (or 0).
Yes deleting a pointer is the same as deallocating memory or freeing memory, etc.
Yes and it calls the appropriate destructor.
In short, yes.
But you have to be careful: if you allocate with p = new sometype() only then should you use delete p. If you allocate using p = sometype[count] always use delete [] p
And one more thing: you should never pair malloc/delete or new/free.