Armen Babakanian
Armen Babakanian

Reputation: 2305

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

Upvotes: 2

Views: 351

Answers (1)

P0W
P0W

Reputation: 47794

Fix :

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

Free memory using :

delete [] str_copy;

Upvotes: 6

Related Questions