Question

Having a lot of trouble with this after sifting through many posts on here. Everything compiles but I get a crash right here during this function which should be dynamically allocating the addresses of one array into this array of pointers. I see one or two memory addresses posted so I'm not sure why it would be crashing during the middle of this.

string *copyArray(string ptrArray[],int sizeArray)
   {
    string **dynamString = new string*[sizeArray];
    int i;

    for (i=0;i<=sizeArray;++i)
        {
         (*dynamString[i]) = ptrArray[i];
         cout << dynamString[i];
        }
    return *dynamString;

}

from main I have:

string *arrPtr;

and the function call

arrPtr = copyArray(arrayOfStrings, arraySize);
Was it helpful?

Solution

for (i=0;i<=sizeArray;++i)

accesses an element behind the array yielding an undefined behavior. Elements are indexed from 0 to sizeArray - 1. Another problem is that you allocate the array of pointers:

string **dynamString = new string*[sizeArray];

and then you are derefencing these pointers although they do not point to any object yet:

(*dynamString[i]) = ptrArray[i];

which also causes an undefined behavior. In case you wanted to create a deep copy, you should allocate the memory for every object as well:

for (i = 0; i < sizeArray; ++i)
{
    dynamString[i] = new std::string(ptrArray[i]);
    cout << *dynamString[i];
}

However you should avoid using C-style arrays always when it is possible and prefer STL containers instead. In this case it could be neat std::vector<std::string> and its constructor that would do the same than your function (just in safer and more reasonable manner with no possible memory leaks):

std::vector<std::string> myStrings(arrayOfStrings, arrayOfStrings + arraySize);

OTHER TIPS

ok I fixed it here. My pointer syntax was incorrect. Here is the correct syntax.

dynamString[i] = &ptrArray[i];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top