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.
Related
I'm new to computer science and I want to know if an object is being deleted if I heap allocate it and then for e. put it in a vector of pointer and then delete the vector. Will the heap object be gone? Here is an example of what I mean.
int main()
{
Type* someHeapObject = new Type();
vector<Type*> someVector(0);
someVector.push_back(someHeapObject);
}
So here's the main part: Can I delete the heap object with delete someVector[0], and then I DON'T have to delete it anymore like this: delete someHeapObject
There are two things that you have to take care of:
Mistake 1
In delete [] someVector you're using the delete [] form when you should be using the delete form because you used the new form and not the new[] form for allocating memory dynamically. That is, delete [] someVector is undefined behavior.
Mistake 2
The second thing that you must take care of is that you should not use two or more consecutive delete's on the same pointer.
Now, when you wrote:
someVector.push_back(someHeapObject);
a copy of the pointer someHeapObject is added to the vector someVector. This means that now there are 2 pointers pointing to the same dynamically allocated memory. One pointer is the someHeapObject and the second is the one inside the vector.
And as i said, now you should only use delete on only one of the pointers. For example you can write:
delete someHeapOjbect; //now the memory has been freed
//YOU CAN'T USE delete someVector[0] anymore
Or you can write:
delete someVector[0]; //now te memory has been freed
//YOU CAN'T USE delete someHeapObject[0] anymore
Note that better option would be to use smart pointers instead explicitly doing memory management using new and delete.
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.
I have some issues about this code:
1) Why the output returns trash if I delete the first cell ?
int b = 1025;
char *v = new char[sizeof(int)];
memcpy(v,&b,sizeof(int));
char *pp = (char*)v;
++pp;
delete v; // is equal delete &v[0]
cout<<"salida"<<*pp;
2) How to delete dynamically allocated memory when i have void* ...
void *pv = v;
is correct
delete pv;
or
delete [](char*) pv;
i think what you are trying to do is deallocating the dynamically allocated memory..
first a pointer is always size of an int.
It only handles data locations(references).
A char pointer can store the address of a char type variable.
A void pointer can store the address of any data type.
so delete option works for both type of data types.
it simply deallocate the space and make it available on heap
A call to new[] needs to be matched by a call to delete[] on the same memory address and using the same pointer type.
A call to new needs to be matched by a call to delete on the same memory address and using the same pointer type.
If you mix things up, then you're invoking undefined behavior and will eventually have problems.
Maybe you'll occasionally be "lucky" and get away with it in certain simple circumstances because of how certain compilers have implemented dynamically allocated memory, but it's still a bad idea and could break at any time. If you try this with a class type which has a destructor, then one common consequence is that the destructor will not be properly run on some or all of the instances. But of course there are other possibilities, such as heap corruption.
So the result of a new char[] statement must be deallocated by a delete[] statement on a pointer of type char*.
You can't delete just one element of a dynamically-allocated array. If you allocate an array with new[], you can only delete the entire array, and you must use delete[], not delete.
Doing
char *v = new char[sizeof(int)];
and then
delete v;
invokes undefined behavior. You need to do delete[] v, and then you can no longer use pp because it points to something that's been deleted.
What exactly are you trying to delete, the char *v or void *pv?
If you want to delete char *v,
delete[] v;
v = NULL; // v still exists, but it's a dangling pointer now, so we set it to NULL (or 0)
Usually when you want to delete something, it has to be paired with new. So I think if you want to delete void *pv, you have to initialize the void pointer to new like this:
void** pv = new(void*); // Create a void pointer using new
pv = (char *)v;
delete pv;
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.
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.