如何为堆中的char []赋值?

dul*_*shi 0 c c++

我的代码出现了_CrtIsValidHeapPointer错误.我终于找出了造成麻烦的原因.
我用下面的例子来说明它:

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);
Run Code Online (Sandbox Code Playgroud)

1)字符串文字使用的空格似乎无法释放?为什么?

2)你用什么方法将valee分配给char数组?
ps:我使用sprintf(c,"hello world");它工作正常.但是更好的方法呢?


看完答案后.我意识到我误解了&c的含义.
我应该用printf("%p\n",c);.

And*_*rey 7

您应该使用复制字符串strcpy.

赋值c="hello world"不会复制字符串的内容,而是将字符串文字的地址分配给指针c.free(c)之后调用时,指针不再是有效的堆地址.

//如果你取消注释2个子句,你会看到地址是相同的

你看到的不是指针的c,而是指针的地址,显然是相同的.


Sha*_*baz 6

您需要使用strcpy或更安全的版本strncpy.请注意,strncpy在没有足够空间的情况下,您必须自己NUL终止字符串.

例子:

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);
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,我们知道有足够的空间c,所以我们可以使用strcpy.如果我们不知道,您可以将字符串剪切到可以处理它的位置:

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);
Run Code Online (Sandbox Code Playgroud)

请注意strncpy,如果没有足够的空间,则字符串不是NUL终止的,您必须手动执行.


边注:

&c是变量的地址c.它与它的内容无关,所以无论你做什么c,&c都不会改变.