Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
このコードが機能しないのはなぜですか? コンパイラ エラーや警告なしで実行時エラーをスローします。
int main(void) { char *korisnik = new char[20]; korisnik = "Bizuterija"; *(korisnik+1) = 'h'; // error here! cout << korisnik << endl; delete[] korisnik; return 0; }
korisnik = "Bizuterija";
korisnikこの行は、格納されて割り当てられnewたアドレスを、文字列リテラルであるため変更できない実行可能ファイルのデータ セグメント内のアドレスに置き換えます。ここで実際にメモリリークを作成します。
korisnik
new
代わりに、文字列の内容を指定されたメモリにコピーしてみてください。
strncpy(korisnik, "Bizuterija", 20);
ところで、C++ を使用するので、必ず使用する必要がありますstd::string。
std::string