increasing char* array

So I wrote this function to increase the length of an char* array by 1. However when I use it, it seems to mess up my heap. When I try deleting the array I get an error: HEAP CORRUPTION DETECTED: after Normal block at (adress of increased array). Is something wrong with the function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  void addToArr(char* array, int arrayLength)
{
    char* oldArray = new char[arrayLength];
    for (int i = 0; i<arrayLength;i++)
    {
        oldArray[i] = array[i];
    }
    array = new char[arrayLength+1];
    for (int i = 0; i<arrayLength;i++)
    {
        array[i] = oldArray[i];
    }
    delete [] oldArray;
}
Last edited on
This function obtains a pointer from new[] at line 8 and loses it forever at line 14, which, on its own, is just a memory leak - you'd need to show the actual program that produces the error you're describing..
I can only guess that perhaps you meant to modify the caller's pointer, in which case your function should take it by reference:
oid addToArr(char*& array, int arrayLength)
but in that case you're missing a delete[]

(of course, the whole thing is moot since C++ has strings)
Last edited on
Thanks a lot! I've been sitting for hours on that one! :)
Topic archived. No new replies allowed.