segmentation fault using c++ copy instead of memcpy -
i'm using c++ copy algorithm copy string literal, (instead of memcpy) i'm getting segmentation fault don't know why though. here code:
#include <iostream> #include <cstring> #include <stdio.h> using namespace std; int main(int argc, char *argv[]) { // if using copy regular pointers, there // no need output iterator, ex: char* some_string = "this 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;
Comments
Post a Comment