implementation of delete[] in c++

Discussion in 'OT Technology' started by BaZ, Jul 3, 2003.

  1. BaZ

    BaZ 2004 ACC Champions

    Joined:
    Jun 12, 2001
    Messages:
    2,005
    Likes Received:
    0
    Location:
    Hokieville, USA
    ok, will this just look at dynamic memory and release it to the heap as long as it sees that its contiguous memory of the same type or what?

    ex:
    Code:
    char* string1 = new char[SIZE];
    char* string2 = new char[SIZE * 2];
    char* string3 = new char[SIZE * 3];
    
    if i do:
    Code:
    delete [] string3;
    delete [] string2;
    delete [] string1;
    
    it will give me a segmentation fault and will die

    my question basically is this: if i do;
    Code:
    delete [] string1;
    
    will the compiler know to free up the space allocated to string1, string2, and string3, since they are contiguous and of the same type?
     
  2. skinjob

    skinjob Active Member

    Joined:
    Jan 6, 2001
    Messages:
    2,337
    Likes Received:
    0
    Location:
    Aztlán
    no, the memory manager will keep track of each allocation and only release the block that you delete.

    Make sure you aren't accidently corrupting string1, string2, or string3 (i.e. make sure you aren't altering the address value stored in each pointer), as that's the most likely culprit.
     
  3. turbo91

    turbo91 New Member

    Joined:
    Jun 14, 2002
    Messages:
    2,521
    Likes Received:
    0
    Location:
    San Diego, CA
    Also, if you are overrunning the buffer of string2 into string3 (i.e., you aren't doing bounds checking), you can destroy the memory tags which help delete know what to delete. Generally, when you allocate memory to a buffer, there is a few bytes prepended to the buffer, and the pointer you receive back is adjusted. This prepended information contains buffer length, etc. If you overwrite this, delete[] can cause a segfault.

    For example,

    Code:
    char *string1 = new CHAR[5];
    char *string2 = new CHAR[5];
    
    strcpy(string1, "1234567890");
    
    You have overrun the buffer of string1. If string1 and 2 are contiguous (which they usually will be in this situation), you have a problem.
     

Share This Page