使用c ++ copy而不是memcpy进行分段错误

时间:2013-10-07 02:43:45

标签: c++ copy segmentation-fault

我正在使用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;
}

1 个答案:

答案 0 :(得分:6)

修复:

char* str_copy = new char[some_string_len];
                         ^ notice square bracket

使用以下内容释放内存:

delete [] str_copy;

相关问题