开发者

Will this code prevent a dangling pointer?

开发者 https://www.devze.com 2023-02-16 00:47 出处:网络
void _this() { stringa= \"i am a\"; // original value of variable a string* modifier = NULL;//pointer is declared 0x0000...
void _this()
{
    string  a        = "i am a"; // original value of variable a
    string* modifier = NULL;     //pointer is declared 0x0000...

    modifier  = &a;              // 0x0000 -> 0x0a //modifier stores the address of 开发者_JS百科a 
    *modifier = "modified";      // 0x0a + 0x0modified... //modifier assigns "modified" to the address of a;

    cout << a << endl << modifier<<"\n"; //shows "modified" + the address of modifier in memory
    modifier = NULL;                     // the pointer(modifier...) now points to nothing....is it no longer "dangling"???
    cout << modifier;                    // shows only zeros...000000000
}


I'm going to assume you are using C++ and not C, and when you say string, you mean ::std::string.

There is no memory leak shown in the code above.

Also, dangling pointers only really matter when objects go out of scope or are deleted. You do neither of those things here.


A dangling pointer is a pointer to invalid memory (that is not NULL). Usually associated with a pointer that was originally pointing at valid memory.

int x = new int(4);    // x valid;
delete x;              // x is now dangling.
                       // It points at memory that does not belong to application

x = NULL;              // x is not dangling.

In your original example the pointer can never dangle as it points at an automatic variable that will always be valid (while modifier is valid). Though if you return modified as a result from the function it would then dangle (if you had not assigned NULL).

Assigning NULL to a pointer after deleting it is very important in C. But no so much in C++ as your pointers should be encapsulated inside a class so that it is no longer available when its use is finished.

std::string    data;   // There is a pointer inside here.
                       // No need to set it to NULL. The destructor handles all that.


There is no dangling pointer in the code. On several of the lines the lefthand (first) comment is wrong while the second comment is correct. For example //0x0000 -> 0x0a //modifier stores the address of a: after that line, modifier holds the address of the variable a which is almost certainly different from the physical address 0x0a.

0

精彩评论

暂无评论...
验证码 换一张
取 消