resize dynamically allocated memory C++ with ASSERT" _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) " -
hi im writing code resize dynamically allocated memory. here part of code initializing:
int size = 1; string *rev = new string[size];
resizing part:
if (j >= size / 2){ size = size * 2; string *temp = rev; rev = new string[size]; memcpy(rev, temp, (size / 2)*sizeof(string)); delete[] temp; // <- here causes error! }
when comment out "delete[] temp" code works fine memory leaks. so, how can handle error message "assert". please help! thanks!
since pointed out assert caused other parts of code. here full version, print words out in reverse order in given sentence.
void reversewords(string &sentence) { char *str = new char[sentence.size()+1]; int size = 1; string *rev = new string[size]; int j = 0; int n = 0; int m = 0; (unsigned int = 0; < sentence.size(); i++){ str[n] = sentence.at(i); n++; if (str[n-1] == ' '){ str[n-1] = '\0'; if (j >= size / 2){ size = size * 2; string *temp = rev; rev = new string[size]; memcpy(rev, temp, (size / 2)*sizeof(string)); delete[] temp; } rev[j] = str; cout << rev[j] << endl; cout << j << endl; j++; memset(str, 0, sentence.size() + 1); n = 0; } } str[n] = '\0'; rev[j] = str; int rev_size; for( rev_size = 0; !rev[rev_size].empty(); rev_size++){ } rev_size--; while (rev_size >= 0){ if (rev_size == 0){ cout << rev[rev_size] << endl; break; } cout << rev[rev_size] << " "; rev_size--; } delete[] rev; delete[] str; return; }
edit: fixed error @πάντα ῥεῖ , @retired ninja. error caused assert misused memcpy function non-pod type. i've changed memcpy to:
(int m = 0; m < j; m++){ rev[m].assign(temp[m]); }
and working! guys.
the reason failing using memcpy
copy std::string
. std::string
not pod type , can't bitwise copied safely, must copy in way uses assignment operator or copy constructor.
a better solution use standard container std::vector<std::string>
or std::deque<std::string>
handle resizing , proper copying.
you simplify algorithm using std::stringstream
split words , store them in container, assume assignment , don't want rewrite function, i'll show minimum need fix problem.
instead of:
memcpy(rev, temp, (size / 2)*sizeof(std::string));
use this:
for(int = 0; < size / 2; ++i) { rev[i] = temp[i]; }
Comments
Post a Comment