I got a _CrtIsValidHeapPointer error with my code. And I finally find out what caused the trouble.
I use the example below to illustrate it:
char* c=(char*)malloc(20*sizeof(char));
//cout<<&c<<endl;
c="hello world";
//cout<<&c<<endl; //if you uncomment the 2 clauses,you'll see the address is the same
//which means the string literal is in the heap
cout<<c<<endl;
free(c);
1) It seemed that spaces used by string literals can’t be freed? Why?
2)What’t the method do you use to assign valee to array of char?
ps: I use sprintf(c,"hello world"); that works fine. But any better way?
After read the answers. I realize that I misunderstand the meaning of &c.
I should use printf("%p\n",c); instead.
You need to use
strcpy, or a safer versionstrncpy. Note that withstrncpy, you have to NUL-terminate the string yourself in case there was not enough space.Examples:
Note that in this case, we know there is enough space in
c, so we can usestrcpy. If we don’t know, you can cut the string up to where you can handle it:Note that in the case of
strncpy, if there is not enough space, the string is not NUL-terminated and you have to do it manually.Side note:
&cis the address of variablec. It has nothing to do with its contents, so no matter what you do withc,&cwill not change.