读书人

请问个华为的笔试题(指针)

发布时间: 2013-03-01 18:33:02 作者: rapoo

请教个华为的笔试题(指针)
本帖最后由 shuyecy 于 2013-02-01 23:27:27 编辑 void Test(void){
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL){
strcpy(str, “world”);
printf(str);
}
}
这个,运行时是会出错,但还是能输出world。str指向的内存不是释放了吗,怎么还能赋值?
[解决办法]
我在VC++ 6.0下单步调试,发现free只是把原先的“hello”清空,然后把指针知道另一个区域,所以str != NULL成立,接着给str赋值也成了,可是printf的时候确实一大堆乱码。。。。。
[解决办法]
free <cstdlib>

void free ( void * ptr );

Deallocate space in memory
A block of memory previously allocated using a call to malloc, calloc or realloc is deallocated, making it available again for further allocations.

If ptr does not point to a block of memory allocated with the above functions, the behavior is undefined.

If ptr is a null pointer, the function does nothing.

Notice that this function does not change the value of ptr itself, hence it still points to the same (now invalid) location.
[解决办法]
free之后指针悬空,但并不为NULL。。
一般,free之后应该置空

free(ptr); 
ptr = NULL;

[解决办法]
楼上说的对。
free(str)把str指向的内存释放掉了,但是str本身还是存在的。
[解决办法]
free仅仅是告诉系统这块内存可以被分配到其他地方使用了,但是指针仍然是指向的这个地址,同样的也可以修改这个地址的内容。因为str被释放后并没有置空(NULL),用了strcpy操作仍然可以继续,printf下的%s只认'\0'这个值,不管这个地址是否被释放
[解决办法]
引用:
本帖最后由 shuyecy 于 2013-02-01 23:27:27 编辑
void Test(void){
char *str = (char *) malloc(100);
strcpy(str, “hello”);
free(str);
if(str != NULL){
strcpy(str, “world”);……


lz 你要搞清楚 释放和分配的实质,内存就在那,你想访问就访问,只是安全与不安全而已.
[解决办法]
一般做法是在free(str)后,执行str=NULL;
free后指针不一定为空。
再对这种野指针操作可能会报错。

读书人网 >C语言

热点推荐