请教个华为的笔试题(指针)
本帖最后由 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;