问题
I'm truely baffled by this throwing an error....
char** results = new char*[numRes]; //this is where it breaks
for(int i = 0; i < numRes; i++)
{
results[i] = new char[64];
}
It's throwing a corruption of the heap error. but surely it should work? Im assigning 4 char* to a list of character pointers so I can pass them into functions etc.
I looked around everywhere but they all seem to be showing the malloc and free... Im using them in classes so I want to stick to c++ new and delete.
Could someone lend me a hand please?
回答1:
What are you doing after you allocate? You only allocated an array of character pointers, you did not allocate space for each element (a pointer). If you try to store items in the elements, you'll run into problems.
For example, if you wanted to store anything in results[0] after your allocation, you would need to allocate to it as well. For example:
results[0] = new char[100]; // NEED TO ALLOCATE BEFORE WRITING TO results[0]!
strcpy(results[0], "Test");
You cannot just copy to results[0] without the allocation. The same holds for any element of results.
回答2:
You are allocating memory for a pointers array. After that you have to allocate memory for every pointer in your array. I think your code should be like this:
int numRes = 4;
char** results = new char*[numRes];
for(int i=0; i<numRes; i++)
{
results[i] = new char;
}
回答3:
If using c++ is it possible to use STL? specifically std::string, and std::list or std::vector classes in your code? Unlike traditional c-strings, which are mere sequences of characters in a memory array, C++ string objects belong to a class with many built-in features to operate with strings in a more intuitive way and with some additional useful features common to C++ containers.
#include <string>
#include <list>
std::list<std::string> results; // create a list of strings
// and populate it
results.push_back("blah");
results.push_back("blah1");
results.push_back("blah2");
...
来源:https://stackoverflow.com/questions/13827284/char-memory-allocation-using-new-operator