Memory Leak or not?

This is a discussion on Memory Leak or not? within the C++ Programming forums, part of the General Programming Boards category; Dose this look right?? Code: struct lworlds{ lworlds(); ~lworlds(); char * name; }; struct game{ lworlds world[10]; } lworlds::lworlds() { ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    411

    Memory Leak or not?

    Dose this look right??
    Code:
    struct lworlds{
    	lworlds();
    	~lworlds();
    	char * name;
    };
    
    struct game{
    	lworlds world[10];
    }
    
    lworlds::lworlds() {
    	name = new char[25];
    }
    
    lworlds::~lworlds() {
    	delete name;
    }

  2. #2
    Registered User kitten's Avatar
    Join Date
    Aug 2001
    Posts
    109
    Nope...
    Code:
    lworlds::~lworlds() {
    	delete name;
    }
    
    // should be:
    
    lworlds::~lworlds() {
    	delete [] name;
    }
    If you allocate an array (new something[]) you must destroy it with delete [].
    Making error is human, but for messing things thoroughly it takes a computer

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    81
    yes, delete the array.

  4. #4
    Registered User
    Join Date
    Aug 2001
    Posts
    411
    As i see it there are 2 ways, either the name is an array of char* or the name is a single element of an array of classes. Will the same delete[] method work for either situation.

  5. #5
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Actually, it's not strictly necessary to call delete with [] for primitives and objects that require no destruction. 'delete name' will free all the memory allocated with 'name = new char[25]'. However if 'name' was an object with a destructor then the [] operator would be required so that the destructor was called for each one. Although, it does no harm calling delete [] on primitives, and it's probably easier to remember to call delete [] whenever you new [].
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory leak in this case?
    By George2 in forum C++ Programming
    Replies: 3
    Last Post: 03-22-2008, 05:05 AM
  2. memory leak in the code?
    By George2 in forum C++ Programming
    Replies: 20
    Last Post: 01-13-2008, 05:50 AM
  3. Is this code memory leak free? ---> POSIX Threads
    By avalanche333 in forum C++ Programming
    Replies: 9
    Last Post: 04-13-2007, 03:19 PM
  4. Any Memory Leak Checking Tool?
    By George2 in forum C Programming
    Replies: 4
    Last Post: 06-21-2006, 11:02 PM
  5. Manipulating the Windows Clipboard
    By Johno in forum Windows Programming
    Replies: 2
    Last Post: 10-01-2002, 09:37 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21