简体   繁体   中英

segmentation fault using c++ copy instead of memcpy

I'm using C++ copy algorithm to copy a string literal, (instead of memcpy) but I'm getting segmentation fault I don't know why though. here is the code:

#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;
}

Fix :

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

Free memory using :

delete [] str_copy;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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