使用 C++ 复制而不是 memcpy 的分段错误

segmentation fault using c++ copy instead of memcpy

本文关键字:memcpy 分段 错误 C++ 复制 使用      更新时间:2023-10-16

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

修复 :

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

使用释放内存:

delete [] str_copy;