且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

释放指针有多精致?

更新时间:2023-11-18 11:07:52

David Scarlett写道:

以下代码是否安全?


No.

SomeType * a,* b;

/ *部分代码.... * /

免费(a);

if(a == b)b = NULL;

a = NULL;




SomeType * a,* b;


/ *有些代码...... * /


if( a == b)b = NULL;


免费(a);


a = NULL;


-

pete


On Sun,2004年5月16日03:25:21 GMT,pete< pf **** *@mindspring.com>写道:
David Scarlett写道:

以下代码是否安全?
否。




嗯。假设a在free()之前有效且b仍然在比较的

点,我不明白为什么你认为这是不安全的。

个人在它之后测试指针的值似乎很奇怪

已被释放(并且你的版本在这个意义上更为传统),

但是因为我们是只测试/ pointer /而不是试图访问

它指向的内存,为什么OP的代码不是安全?

-leor

SomeType * a,* b;

/ *有些代码.... * /

免费( a);

if(a == b)b = NULL;

a = NULL;



SomeType * a, * b;

/ *有些代码.... * /

if(a == b)b = NULL;

免费( a);

a = NULL;




David Scarlett写道:
以下代码是否安全?


No.

SomeType * a,* b;

/ *部分代码.... * /

免费(a);


该标准未规定是否更改了。它可能仍然

包含相同的值,它可能设置为NULL,或者它可能是一些

其他该死的值。


if(a == b)b = NULL;


相当无比的比较,对吧?

a = NULL;

谢谢。



Is the following code safe?

SomeType *a, *b;

/* Some code.... */

free(a);

if ( a == b ) b = NULL;

a = NULL;

Thanks.

--
David Scarlett

dscarlett@_ _ _ _ _ _ _ _
_ _ _ _ _ optusnet.com.au

David Scarlett wrote:

Is the following code safe?
No.
SomeType *a, *b;

/* Some code.... */

free(a);

if ( a == b ) b = NULL;

a = NULL;



SomeType *a, *b;

/* Some code.... */

if ( a == b ) b = NULL;

free(a);

a = NULL;

--
pete


On Sun, 16 May 2004 03:25:21 GMT, pete <pf*****@mindspring.com> wrote:
David Scarlett wrote:

Is the following code safe?
No.



Hmmm. Assuming a was valid before the free() and b still is at the
point of the comparison, I don''t get why you think this is unsafe.
Personally, it seems strange to test the value of a pointer after it
has been freed (and your version is more conventional in that sense),
but since we''re only testing the /pointer/ and not trying to access
the memory it is pointing to, why wouldn''t the OP''s code be "safe"?
-leor

SomeType *a, *b;

/* Some code.... */

free(a);

if ( a == b ) b = NULL;

a = NULL;



SomeType *a, *b;

/* Some code.... */

if ( a == b ) b = NULL;

free(a);

a = NULL;




David Scarlett wrote:
Is the following code safe?
No.
SomeType *a, *b;

/* Some code.... */

free(a);
The standard does not specify whether a is changed. It might still
contain the same value, it might be set to NULL, or it might be some
other damn value.

if ( a == b ) b = NULL;
Pretty pointless comparison, huh?

a = NULL;

Thanks.