Is this a memory leak? - c++

char *pointer1;
char *pointer2;
pointer1 = new char[256];
pointer2 = pointer1;
delete [] pointer1;
In other words, do I have to do delete [] pointer2 as well?
Thanks!

Nope, that code is fine and won't leak memory.
You only have to use delete[] once because you've only used one new to allocate an area for memory, even though there are two pointers to that same memory.

A simple rule: you need as many deletes as there are news. Even better, use something like a smart pointer or a container to take care of it for you.
And another minor point: pointer2 is becoming a "dangling pointer" once you call delete on pointer1.

It's not a leak, but it is asking for trouble. pointer2 is pointing to who-knows-what as soon as you delete pointer1. It's what's called a "dangling pointer". Using it can in the best case cause a segfault, and in the worst case can cause mysterious data mangling in anything that ends up allocated that same spot.

While it doesn't leak memory, if you want to be explicit, you should set both point1 and point2 to NULL (and initialize them that way too.)

Additionally, consider using boost::shared_ptr<> from the Boost libraries. It's the greatest thing since sliced bread.
typedef boost::shared_ptr<TypeX> StrRef;
foo() {
StrRef pointer1(new TypeX);
while(something) {
StrRef pointer2 = pointer1;
// do stuff
}
return;
}
The data (TypeX) will be deleted when the last pointer to it goes out of scope. You can do something similar with the built-in auto_ptr<> type, if you don't need a reference count:
typedef auto_ptr<TypeX> StrRef;
foo() {
StrRef pointer1(new TypeX);
while(something) {
TypeX * pointer2 = pointer1.get();
subroutine(pointer2);
if (condition) return;
}
return;
}
Whenever pointer1 goes out of scope, it will delete the data. The advantage with this is that you don't have to remember put a delete before the return statement at the bottom, and if pointer1 goes out of scope for any other reason (i.e. return from the middle of the loop, or subroutine() throws an exception, then the data will still be deallocated properly.
I haven't tested this code, so you'll have to check the docs for auto_ptr<> and boost::shared_ptr<> yourself.
I highly recommend using the Boost libraries as much as possible. It's written by pro's it's basically a staging area for extensions to C++.

delete deletes the memory that was allocated by new. Since you only have one new you only need one delete.

Only use Delete when you've used New
Good practive is to set pointer2 to NULL, but you won't have a memory leak if you don't

Every new should have one, and only one, matching delete. If you deleted the other pointer, you would break that rule.

What you do here is just tell that memory block allocated by new char[256] would be pointed by pointer1 and pointer2 at the same moment.
It would be a memory leak if you wrote delete[] pointer2; statement after.

No, you do not have to delete[] pointer2 because you have not allocated memory for it!
The statement pointer2 = pointer1 makes pointer2 point to the same memory address as pointer1, does not allocate any extra memory for it.

Here's the gap in your thinking: You don't delete pointers — you delete memory. You simply use a pointer to identify the block of memory to be freed. Since the two variables point to the same memory, deleting one is precisely equivalent to deleting the other. In other words, deleting both is the same as deleting one of them twice — which is obviously wrong.

Related

Pointer in a class

I have the following below code snippet
class test{
private:
int *ptr;
public:
test(int *myptr){
ptr = myptr;
}
~test(){
delete ptr;
}
};
int main(){
int* myptr = new int;
*myptr = 10;
test obj(myptr);
delete myptr;
}
Is there a memory leak happening in this program, if I dont do a new to pointer in the class will space be allocated for that pointer?
Rule of thumb for dealing with allocating member: every new/new[] should be paired with exactly one delete/delete[]. If you are missing the delete, then you have a memory leak (you have allocated memory that you never clean up). If you are delete-ing multiples times, as you are doing in this code example, you will have memory corruption issues.
How are you delete-ing multiple times? In main(), you allocate a pointer:
int* myptr = new int;
You give a copy of that pointer to your test object, obj. Then, at the end of the scope we have:
{
// ...
delete myptr;
~test(); // implicit, which also does delete myptr
}
Only one of those two places should be responsible for delete-ing the pointer. Which one is based on the semantics of your code. Does test own the pointer? In which case, it should delete it but main() should not. Does it simply observe the pointer? In which case, it should not delete it. With C++11, we have new smart pointers to express this idea better.
I'd encourage you to browse the definitive C++ book list as concepts like this are very crucial to understanding C++ but also very difficult to explain properly in a short Q&A format.
You should only delte a pointer once in ~test() or delete directly
*** Error in `./a.out': double free or corruption (fasttop): 0x08d13a10 ***
Consider using std::shared_ptr<int> or std::unique_ptr<int>, since direct memory management is discouraged in modern C++ unless you've a reason to do so.
You can read about semantics differences of smart pointers here, and the reference for them is here.
It will crash when exit main function, a allocated in heap memory can't be release two times
What will happen in your instance is that the pointer will be given to delete in main(), then the same pointer value will be given a second time to delete in the destructor of obj. This is undefined behaviour, so it might work, or it might not, in any case, it isn't guaranteed to work, and therefore such a construct should not be used.
Ordinarily you would establish ownership rules, e.g. whether the constructor “takes ownership” (and is therefore responsible for freeing resources) is up to you, but typically, and especially in modern C++, ownership semantics can be clearly achieved by using std::unique_ptr and std::shared_ptr.
Most importantly, whichever method you use to determine ownership, make sure you are consistent! Avoid complicated ownership semantics, as it will make it much more difficult to detect memory-related issues (or more generally, resource-related issues).
Contrary to what other people have said: you do not delete pointers in C++, but objects.
What's the difference?
Let's simplify your code a bit:
int *myptr = new int; // 1
int *ptr = myptr; // 2
delete myptr; // 3
delete ptr; // 4
As far as the usage of new and delete is concerned, this is the same code - I've just removed the class, since it's not relevant to the point here.
This code does the following:
new int allocates an int, and returns its address. The address is then stored in myptr.
The address is copied to ptr. Both ptr and myptr contain the address of the int that was just allocated.
The int is deallocated.
The int is deallocated... but it was already deallocated? Oops!
If you're lucky, your program will crash at this point.
delete myptr; has nothing to do with the variable myptr, except that myptr holds the address of the thing to delete.
It doesn't even have to be a variable - you could do delete new int; (although it wouldn't be very useful) or delete someFunctionThatReturnsAnAddress();, or int *p = 1 + new int[2]; delete [] (p - 1);.
Your class has only a reference of the allocated integer. Consider to declare it int const* ptr, then you cant delete it inside the class.
You should remove delete ptr from the destructor.
Usually the scope which is allocating something is responsible for freeing it. In your case the main routine is allocating and has to free.
For your question "Is there a memory leak happening in this program", the answer is No, but an exception is rasing.
Your code logic is not good, you should delete the pointer at where it was created. In this example, you shouldn't delete ptr in destructor function.

Delete a pointer getting AccessViolationException

I have a class pointer declaration:
MyClass* a;
In destruction method I have:
if (a)
{
delete a;
a= NULL;
}
I got a problem when delete the pointer a:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
What is the cause of the problem and how can I get rid of it?
With your current declaration:
MyClass* a;
a gets a random value. If you never give it a valid value later, such as:
a = new MyClass();
It will point to an unknown place in memory, quite probably not a memory area reserved for your program, and hence the error when you try to delete it.
The easiest way to avoid this problem is to give a a value when you declare it:
MyClass* a = new MyClass();
or, if you cannot give it a value when you declare it (maybe you don't know it yet), assign it to null:
MyClass* a = 0;
By the way, you can remove the test (if (a)) from your code. delete is a no-op on a null pointer.
Use smart pointer to free memory. delete in application code is always wrong.
unless you have initialized the pointer to something after this:
MyClass* a;
the pointer a will hold some random value. So your test
if (a) { }
will pass, and you attempt to delete some random memory location.
You can avoid this by initializing the pointer:
MyClass* a = 0;
Other options are that the object pointed to has been deleted elsewhere and the pointer not set to 0, or that it points to an object that is allocated on the stack.
As has been pointed out elsewhere, you could avoid all this trouble by using a smart pointer as opposed to a bare pointer in the first place. I would suggest having a look at std::unique_ptr.
How did you allocate the memory that a points to? If you used new[] (in order to create an array of MyClass), you must deallocate it with delete[] a;. If you allocated it with malloc() (which is probably a bad idea when working with classes), you must deallocate it with free().
If you allocated the memory with new, you have probably made a memory management error somewhere else - for instance, you might already have deallocated a, or you have written outside the bounds of some array. Try using Valgrind to debug memory problems.
You should use
MyClass* a = NULL;
in your declaration. If you never instantiate a, the pointer is pointing to an undefined region of memory. When the containing class destructor executes, it tries to delete that random location.
When you do MyClass* a; you declare a pointer without allocating any memory. You don't initialize it, and a is not necessarily NULL. So when you try to delete it, your test if (a) succeeds, but deallocation fails.
You should do MyClass* a = NULL; or MyClass* a(nullptr); if you can use C++11.
(I assume here you don't use new anywhere in this case, since you tell us that you only declare a pointer.)

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.

Unclear about `delete` and pointers

Say we have a piece of code:
//...
class A
//...
A* myA = new A();
A* myPointerToMyA = myA;
delete myA;
delete myPointerToMyA; // this is wrong, no?
//...
The last line does the exact same thing as the one above it, correct? So I would now be deleteing an invalid/NULL pointer?
I understand this may be a stupid question, but still, I need some reassurance.
Indeed it is wrong. And in constrast to one of the other comments, it's not because you didn't allocate it with new.
Both myA and myPointerToMyA point at the same thing. Deleting through either of them is fine - but you can only delete it once legitimately because they point at the same thing - it is what is pointed at that is deleted, not the pointer itself.
There is nothing wrong with having two pointers to the same thing, but you musy keep track of who owns it, and who is responsible for deleting it.
In this instance, deleting a pointer to a deleted object, the behavior is 'undefined' - the run-time can do what it likes! (I can pretty much guarantee you won't like it...)
Yes, it's wrong. When you used delete, you're not deleting the pointer. Rather, you're deleting what it points to. So, when you use delete on a pointer, the memory that that pointer points to is freed. Any other pointer that points to that memory is now pointing to unallocated memory and is a dangling pointer. Using a dangling pointer results in undefined behavior, and it certainly isn't valid to try and free already freed memory, so using delete on a dangling pointer is definitely wrong. It will likely result in a segmentation fault.
You are correct.
So I would now be deleteing an invalid/NULL pointer?
Well, technically it's only invalid, because nothing was set to NULL. It's ok to delete a NULL pointer.
What you are getting here is the following:
A* myA = new A(); // myA is now equal to 0x11110000 for example(!)
A* myPointerToMyA = myA; // myPointerToMyA is now equal to 0x11110000
delete myA; // equal to delete (A*)(0x11110000)
delete myPointerToMyA; // equal to delete (A*)(0x11110000)
Two last lines are equal in the end. This code will lead to undefined behavior.
Yes it is wrong. The memory allocated for allocated with new A() and released with delete myA. One thing to note is that while delete myPointerToMyA is an attempt to delete an invalid pointer, it isn't an attempt to delete a NULL pointer because myPointerToMyA is not equal to NULL.
2 pointers point to the same object. The object gets destroyed after you call delete myA; for the first time. When you call delete for the second time(delete myPointerToMyA;) you are trying to delete object more than once, and the result of such action is undefined(usually you get runtime exception).

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.