2

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;
}
2
  • 2
    Is there a good reason you can't use std::string? Commented Oct 7, 2013 at 2:46
  • It's for learning purposes. I was trying out the copy algorithm with output iterators, and in a book that I'm reading now, describes that I can replace the iterators in the copy call with low level pointers. Commented Oct 7, 2013 at 6:39

1 Answer 1

6

Fix :

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

Free memory using :

delete [] str_copy;

Sign up to request clarification or add additional context in comments.

2 Comments

@ArmenB and before you ask why ? So, If () is used, the item is value-initialized.
@AmenB that would be the technical description for saying you were allocating a single char and initializing it to the value of some_string_len. I'm surprised your compiler didn't issue a warning about the down-convert between int and char.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.