I believe that you are misunderstanding what the difference is between a memory leak and a buffer overflow.
What is a buffer overflow?
A buffer overflow occurs when we have some piece of memory that we are going to store some data in. And when we store that data, we put too much data there. For example:
int x[4];
x[0] = 7;
x[1] = 8;
x[2] = 9;
x[3] = 10;
x[4] = 11; // <-- Buffer Overflow!
Your code exhibits a potential buffer overflow because cin
doesn't know how much memory you've allocated. And there's no real method to tell it that when using char *
arguments. So in your first example, if you were to write any string longer than the empty string, you would cause a buffer overflow. Likewise, if you were to write more than 30 characters (including the null character) to the second example, you would also cause a buffer overflow.
What is a memory leak?
A memory leak is traditionally represented this way:
char *x = new char[30];
x[0] = 'a';
x[1] = '\0';
x = new char[10]; // <-- Memory Leak!
At this point in the code, you have no ability to call delete[]
on the first allocation. You have no variable that points to that pointer. That is a memory leak.
What does delete[] do?
Let's consider that there is some bucket somewhere that can give us chunks of memory. We can grab chunks of memory from that bucket via new
and new[]
. When we use delete
and delete[]
, we return those chunks of memory back to the bucket.
The agreement that we make with new
and delete
is that once we call delete
on a piece of memory, we don't continue to use it. We don't do this, because the system may reuse that piece of memory, or it may have removed all ability to access that pointer all together.
How could this possibly work?
You have this piece of code:
char *x = new char;
cin >> x;
I'd like to tell you that it's basically the same as this piece of code:
char y;
cin >> &y;
In both cases, you've allocated space for only one char. So when we call delete
on x
, we're only deleteing one char. The part of the code there that will likely break is that cin
will think that there is enough memory allocated for whatever string it is going to try and write to that pointer.
The fact is, there probably isn't enough space. There's only space for one char. And even the string "a"
, takes up 2 chars.