0

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.

4

4 回答 4

7

You should copy the string using strcpy.

The assignment c="hello world" doesn't copy the contents of the string, but assigns the address of the string literal to the pointer c. When you call free(c) afterwards, the pointer is not a valid heap address any more.

//if you uncomment the 2 clauses,you'll see the address is the same

What you see is not the value of pointer c, but the address of the pointer, which is obviously the same.

于 2012-08-01T09:26:30.883 回答
6

You need to use strcpy, or a safer version strncpy. Note that with strncpy, you have to NUL-terminate the string yourself in case there was not enough space.

Examples:

char *some_other_string = ...;
int len = strlen(some_other_string);
char *c = malloc((len + 1) * sizeof(*c));
if (c == NULL)
    // handle error

strcpy(c, some_other_string);

free(c);

Note that in this case, we know there is enough space in c, so we can use strcpy. If we don't know, you can cut the string up to where you can handle it:

char *some_other_string = ...;
char *c = malloc((MAX_LEN + 1) * sizeof(*c));
if (c == NULL)
    // handle error

strncpy(c, some_other_string, MAX_LEN);
c[MAX_LEN] = '\0';

free(c);

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:

&c is the address of variable c. It has nothing to do with its contents, so no matter what you do with c, &c will not change.

于 2012-08-01T09:27:24.807 回答
3
c = "hello world";

You are modidying the c pointer to the pointer to the "hello world" string literal. This does not copy the string but just modify the c pointer. You have to use the strcpy function to copy a string in an array of char.

strcpy(c, "hello world");
于 2012-08-01T09:27:29.313 回答
0

如果您使用该语言的 C++ 部分,这一切都由std::stringC++ 标准库中的 处理。

std::string c = "hello world"; 
cout << c << endl;

完毕!

您不必手动管理任何内容。

于 2012-08-01T09:33:51.043 回答