“免费”的使用 [英] The use of "free"
本文介绍了“免费”的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么会出现这种错误?
typedef char * string;
int main(无效)
{
string str;
str =" ajsdklfajsdf";
printf("%s \ n",str);
free(str);
printf("%s\ n",str);
}
Why this error occurs??
typedef char *string;
int main(void)
{
string str;
str="ajsdklfajsdf";
printf("%s\n",str);
free(str);
printf("%s\n",str);
}
推荐答案
Mars< Mars @ mars>写道:
Mars <Mars@mars> wrote:
为什么会出现这个错误?
哪个错误?
typedef char * string;
我希望你意识到char指针不是字符串...
int main(void)
{
string str;
str =" ajsdklfajsdf";
printf("%s \ n",str);
free(str);
''str''不是指向你从malloc(),calloc()或
realloc()获得的内存的指针。在这种情况下,你不允许在
上调用free()指针。
printf("%s \ n",str);
}
Why this error occurs??
Which error?
typedef char *string;
I hope you realize that a char pointer isn''t a string...
int main(void)
{
string str;
str="ajsdklfajsdf";
printf("%s\n",str);
free(str);
''str'' isn''t a pointer to memory you got from malloc(), calloc() or
realloc(). And in that case you''re not allowed to call free() on
that pointer.
printf("%s\n",str);
}
你在这里缺少一个return语句,至少对于一个C89编译器来说。
main()返回一个int。
问候,Jens
-
\ Jens Thoms Toerring ___ Je *********** @ physik.fu-berlin.de
\ __________________________ http://www.toerring.de
Mars写道:
typedef char * string;
int main(void)
{
string str;
STR = QUOT; ajsdklfajsdf英寸;
坏主意,因为你仍然无法修改内存''str''指向。
printf("%s \ n" ;,str);
free(str);
typedef char *string;
int main(void)
{
string str;
str="ajsdklfajsdf";
Bad idea, as you still can''t modify the memory ''str'' points to.
printf("%s\n",str);
free(str);
你只能使用免费()指针从以前的调用中获取
malloc()或相关功能。
Uli
You can only use free() with pointers reveived from previous calls to
malloc() or related functions.
Uli
因为你没有分配 ajsdklfajsdf" ;.你必须这样做才能使它成为可以自由的:
int main(无效)
{
string str;
/ *分配字符串的内存* /
if(!(str = malloc(strlen(") ajsdklfajsdf")+ 1))){
返回-1;
}
/ *将字符串放入已分配的记忆* /
strcpy(str," ajsdklfajsdf");
/ *免费分配内存* /
免费(str);
/ *将释放的指针设置为NULL总是很聪明* /
str = NULL;
}
基本上你不必担心你在
写的例子中是免费的。
-
bjrnove
Because you didn''t allocate "ajsdklfajsdf". You would have to do
something like this to make it be freeable:
int main(void)
{
string str;
/* Allocate memory for the string */
if(!(str = malloc(strlen("ajsdklfajsdf") + 1))){
return -1;
}
/* Put the string into the allocated memory */
strcpy(str, "ajsdklfajsdf");
/* Free the allocated memory */
free(str);
/* It''s always smart to set the freed pointer to NULL */
str = NULL;
}
Basicly you wouldn''t have to worry about free at all in the example you
wrote.
--
bjrnove
这篇关于“免费”的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文