繁体   English   中英

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

[英]segmentation fault using c++ copy instead of memcpy

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

解决:

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

可用内存:

delete [] str_copy;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM