The void del function cannot set the class pointer inside of obj_slot to NULL;
class test_object {
public:
char *name;
int id;
};
int current_amount;
test_object *obj_slot[512];
void add(test_object *obj)
{
if(current_amount < 512)
{
obj->id = current_amount;
obj_slot[current_amount] = obj;
current_amount ++;
}
else {
std::cout<<"max exceeded";
}
}
void printList(char *status){
printf("%s\n",status);
for(int i = 0 ; i < current_amount ; i ++)
{
printf("list object id %i; string is %s,pointer:%p\n",obj_slot[i]->id,obj_slot[i]->name,obj_slot[i]);
}
}
void del(test_object *obj)
{
printList("before:");
if(!obj)
return;
printf("deleting %s id %i,pointer %p\n",obj->name,obj->id,obj);
for(int i = obj->id ; i < current_amount - 1 ; i ++)
{
obj_slot[i] = obj_slot[i + 1];
}
delete obj;
obj = NULL;
current_amount--;
printList("after:");
}
//this is the test program:
int main(int argc, char **argv) {
std::cout << "Hello, world!" << std::endl;
for(int i = 0 ; i < 5; i ++)
{
test_object *test = new test_object();
char a[500];
sprintf(a,"random_test_%i",i);
test->name = (char *)malloc(strlen(a) + 1);
strcpy(test->name,a);
add(test);
}
test_object *test = new test_object();
test->name = "random_test";
add(test);
del(test);
printf("test pointer after delete is %p\n",test);
return 0;
}
I’ve set the pointer address that I want to delete in the del function to NULL; but the console output is still this:
before:
list object id 0; string is random_test_0,pointer:0x706010
list object id 1; string is random_test_1,pointer:0x706050
list object id 2; string is random_test_2,pointer:0x706090
list object id 3; string is random_test_3,pointer:0x7060d0
list object id 4; string is random_test_4,pointer:0x706110
list object id 5; string is random_test,pointer:0x706150
deleting random_test id 5,pointer 0x706150
after:
list object id 0; string is random_test_0,pointer:0x706010
list object id 1; string is random_test_1,pointer:0x706050
list object id 2; string is random_test_2,pointer:0x706090
list object id 3; string is random_test_3,pointer:0x7060d0
list object id 4; string is random_test_4,pointer:0x706110
test pointer after delete is 0x706150
* Exited normally *
That’s because in the
delfunction the variableobjis a local variable, and all changes to it will not be visible outside of that function. If you want to modify it you should pass it as a reference instead: