开发者

what is the proper way to delete a pointer in an array?

开发者 https://www.devze.com 2023-01-06 13:58 出处:网络
//the setup tiles = new Tile **[num_bands]; for( int i = 0 ; i < num_bands ; i++ ) tiles[i] = new Tile *[num_spokes];
//the setup
tiles = new Tile **[num_bands];
for( int i = 0 ; i < num_bands ; i++ )
tiles[i] = new Tile *[num_spokes];  

for(int i=0; i < num_bands; i++){
    for(int ii=0; ii < num_spokes; ii++){
        tiles[i][ii] = 0; 
    }
}


 //the problem
delete tiles[1][1];

When I delete a tile, tiles[1][1] still holds an address. I thought it should be a null pointer or 0x0, but its not. Am I d开发者_StackOverflow社区eleting this wrong?


delete isn't supposed to null the pointer; it's your own responsibility to do that if you want to.

Basically, delete just means "I no longer need the memory at this address, so you can use it for something else." - it doesn't say anything about what value pointers that pointed to the freed address will have.


C++ delete does not necessarily set the address to NULL after deleting, as explained here: in a previous SO question


Use smart pointers that free their own resources. In C++, it's typically considered to be very bad to deal with your own resources unless you're explicitly a resource manager class.


Another way of saying what others have pointed out:

1) A pointer points to a location in memory.

2) Delete simply frees the memory of where said pointer was pointing to. However the pointer will remain pointing to the same place.

3) You must then nullify the pointer yourself if you so desire.


Unless I'm that rusty on my C++, setting a pointer = 0 doesn't actually free the memory. What you're doing is essentially leaking your whole matrix.

0

精彩评论

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

关注公众号