1

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);
2
  • Please consider using a vector. Commented Oct 29, 2013 at 23:27
  • 1
    Why not use vector<string> ? Don't manage memory yourself. Commented Oct 29, 2013 at 23:27

2 Answers 2

7
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);
Sign up to request clarification or add additional context in comments.

1 Comment

ok I see what you are saying and I fixed that, unfortunately it still crashes after 2 out of 27.
1

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

dynamString[i] = &ptrArray[i];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.