I've been wondering about memory leaks, and how they are created. Especially reguarding *char variables. First a question, in what cases would you need to delete memory in order to keep it from leaking?
I've been coding something, and I'm curious if it leaks, and why if it does. Suppose I had a global pointer variable. Within my main, I allowcated an array of size 50 for this g_pointer. Then a function has another char pointer variable. It is allowcated an array of 50 within the function. In the function the pointers swap. The code looks like this.
Code:
char *g_ch1;
void foo() {
char *swap;
char *ch2 = new char[50];
ch2[0] = 'b';
ch2[1] = 'l';
ch2[2] = 'e';
ch2[3] = 'h';
swap = g_ch1;
g_ch = ch2;
ch2 = swap;
}
void main() {
g_ch = new char[50];
foo();
cout<<g_ch1<<endl;
}
naturally you'll see "bleh" on the screen. But I'm curious about *ch2. What happens to it? Would it be safe to delete ch2 at the very end of the function because it's not used in the program? Is it not nessary?