Initializing a char array through passed pointer segfaults

Posted by Bitgarden on Stack Overflow See other posts from Stack Overflow or by Bitgarden
Published on 2012-06-10T22:30:24Z Indexed on 2012/06/10 22:40 UTC
Read the original article Hit count: 181

Filed under:
|

Ie., why does the following work:

    char* char_array(size_t size){
            return new char[size];
    }

    int main(){
            const char* foo = "foo";
            size_t len = strlen(foo);
            char* bar=char_array(len);
            memset(bar, 0, len+1);
    }

But the following segfaults:

    void char_array(char* out, size_t size){
            out= new char[size];
    }

    int main(){
            const char* foo = "foo";
            size_t len = strlen(foo);
            char* bar;
            char_array(bar, len);
            memset(bar, 0, len+1);
    }

© Stack Overflow or respective owner

Related posts about c++

Related posts about chararray