strcpy versus = operator

Sep 16, 2009 at 6:02pm
I have the below code snippet, a very elementary one.

void main(){
char * p = (char*)malloc(sizeof(char*)*13);
*p = "Hello World";
cout<<*p<<endl;
free(p);
}

The above gives a debug assertion failed.

void main(){
char * p = (char*)malloc(sizeof(char*)*13);
strcpy(p, "Hello World");
cout<<*p<<endl;
free(p);
}
This works perfectly fine.

Can someone give the reason for this? Is it because strcpy does a deep copy while = is a shallow copy.

Thanks
Sep 16, 2009 at 6:10pm
"Hello World" returns a pointer to a const char.
When you try to free(p), you are trying to free the reassigned p which now points to that unmodifiable part of memory.
If you can use C++ use std::string
Sep 16, 2009 at 6:18pm
I'm surprised the first one compiled at all.
*p = "Hello World"; //this ain't right

and in both examples this line(not exactly wrong - but......:
char * p = (char*)malloc(sizeof(char*)*13); // why sizeof(char*)
Sep 16, 2009 at 6:40pm
main is supposed to return int. And also, why are you using malloc and free? Do it the proper C++ way.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstring>

int main()
{
    char *p = new char[13];
    strcpy(p, "Hello World");
    std::cout << p << std::endl;
    delete[] p;
    return 0;
}
Topic archived. No new replies allowed.