Reputation: 866
Hello I know that in C if I do the following I will get a memory leak:
int *b = malloc(128*sizeof(int));
b = b+25;
free(b);
Now I was trying to understand if the new[] and the delete[] operators have the same problem or not. Would I get a memory leak if I write the following ?
int* bcpp = new int[128];
bcpp +=25;
delete[] bcpp;
Upvotes: 0
Views: 78
Reputation: 45654
7.22.3.3 The
free
function#include <stdlib.h> void free(void *ptr);
2 The
free
function causes the space pointed to byptr
to be deallocated, that is, made available for further allocation. Ifptr
is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call tofree
orrealloc
, the behavior is undefined.
3 Thefree
function returns no value.
Passing a pointer to delete []
which does not come from new []
in C++ has the same adverse effect as passing a pointer to free
which does not come from a corresponding allocation function in C and C++.
Upvotes: 2
Reputation: 50053
free
or delete[]
must be invoked on pointers returned by malloc
or new[]
or on a nullptr
. If invoked on anything else, your program has undefined behavior.
This means that in both your examples, you could get a leak or a free pizza or whatever, everything is legal.
An example for a leak in C++ would be the following:
void fun () {
int* p = new int[128];
}
Now you have no way to delete p
, so the memory pointed to by p
is leaked.
Upvotes: 3