Thread: Question about Memory Leaks with *char

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User Diamonds's Avatar
    Join Date
    Oct 2002
    Posts
    68

    Question about Memory Leaks with *char

    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?
    Last edited by Diamonds; 12-16-2002 at 12:58 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer memory question
    By Edo in forum C++ Programming
    Replies: 5
    Last Post: 01-21-2009, 03:36 AM
  2. Memory question
    By John_L in forum Tech Board
    Replies: 8
    Last Post: 06-02-2008, 10:06 PM
  3. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  4. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM
  5. Is it necessary to write a specific memory manager ?
    By Morglum in forum Game Programming
    Replies: 18
    Last Post: 07-01-2002, 01:41 PM