Sep 16, 2009 at 6:02pm Sep 16, 2009 at 6:02pm UTC
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 Sep 16, 2009 at 6:10pm UTC
"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 Sep 16, 2009 at 6:18pm UTC
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*)