我正在使用C ++复制算法来复制字符串文字(而不是memcpy),但是我遇到了分段错误,我不知道为什么。这是代码:
#include <iostream>
#include <cstring>
#include <stdio.h>
using namespace std;
int main(int argc, char *argv[]) {
// if using copy with regular pointers, there
// is no need to get an output iterator, ex:
char* some_string = "this is a long string\n";
size_t some_string_len = strlen(some_string) + 1;
char* str_copy = new char(some_string_len);
copy( some_string, some_string + some_string_len, str_copy);
printf("%s", str_copy);
delete str_copy;
return 0;
}
答案 0 :(得分:6)
修复:
char* str_copy = new char[some_string_len];
^ notice square bracket
使用以下内容释放内存:
delete [] str_copy;