我也評論了代碼,表明我的擔憂,我會很感激任何幫助。我在這個C++代碼中做錯了什麼?我應該知道的最佳做法是什麼?
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
int main()
{
std::string str ("Please split this sentence into tokens");
const char * cstr = (char *)malloc((sizeof(char)) * str.size());
cstr = str.c_str();
const char *p = std::strtok((char *)cstr, " ");
while (p != 0) {
std::cout << p << '\n';
p = std::strtok(NULL, " ");
}
delete[] cstr; // Why not "delete cstr;"
return 0;
}
我簡單的編譯的 「g ++ -Wall code.cpp」,我跑了./a.out如下:
請這句話分成令牌 *錯誤`。 /a.out':雙重空閒或損壞(fasttop):0x0000000001434c20 * ======= Backtrace:========= /usr/lib/libc.so.6(+0x70c4b) [0x7f2d781a8c4b] /usr/lib/libc.so.6(+0x76fe6)[0x7f2d781aefe6] /usr/lib/libc.so.6(+0x777de)[0x7f2d781af7de] ./a.out[0x400c97] /USR /升IB/libc.so.6的(__ libc_start_main +的0xf1)[0x7f2d78158291] ./a.out[0x400afa] =======存儲器映射:======
投票結果過於寬泛,因爲它需要編寫一半的C++書來體面地解釋這裏出現的所有錯誤。請閱讀其中一本很好的現有C++入門書籍。 –
你讓點cstr到string :: c_str(const char *)的結果,然後用strtok()修改它 - UB – LWimsey
第一行開始沒問題。然後突然出現了一個瘋狂的'malloc',它從那裏走下坡...... –