Reputation: 123
I'm trying to figure out how to set a struct pointer to NULL within a function. Here is my code.
struct object
{
char* name;
int type;
};
struct object* createObject(char* new_name, int new_type)
{
struct object* new_object = (struct object*) malloc(sizeof(struct object));
new_object->name = (char*) malloc(sizeof(char) * (strlen(new_name) + 1));
strcpy(new_object->name, new_name);
new_object->type = new_type;
return new_object;
}
void freeData(struct object* clearedObject)
{
free(clearedObject->name);
clearedObject->name = NULL;
clearedObject->type = 0;
}
void freeObject(struct object* deadObject)
{
free(deadObject);
deadObject = NULL;
}
int main(void)
{
struct object* my_object = createObject("Test", 1234);
printf("Pointer to Object: %p\n", my_object);
printf("Pointer to Name : %p\n", my_object->name);
printf("Name: %s\n", my_object->name);
printf("Type: %d\n", my_object->type);
printf("\n");
freeData(my_object);
printf("Pointer to Object: %p\n", my_object);
printf("Pointer to Name : %p\n", my_object->name);
printf("Name: %s\n", my_object->name);
printf("Type: %d\n", my_object->type);
printf("\n");
freeObject(my_object);
printf("Pointer to Object: %p\n", my_object);
}
This is what the code outputs:
Pointer to Object: 005E17B8
Pointer to Name : 005E17D8
Name: Test
Type: 1234
Pointer to Object: 005E17B8
Pointer to Name : 00000000
Name: (null)
Type: 0
Pointer to Object: 005E17B8
Why can I set the pointer to the struct's name to NULL within a function, but not the actual struct pointer itself? How can this be done?
I need to set my_object to NULL from within the function, how would this be possible?
Thanks.
Upvotes: 0
Views: 566
Reputation: 310950
Define the function the following way
void freeObject(struct object ** deadObject)
{
free( *deadObject);
*deadObject = NULL;
}
And call it like
freeObject( &my_object );
The problem with your original function is that the parameter is a local variable of the function. Any changes of a local variable does not influence on the original argument.
Upvotes: 3