If I dynamically allocated a space for a pointer, list this:
int *a = (int*)malloc(sizeof(int));
should I free a when the code is done? Thanks!
If I dynamically allocated a space for a pointer, list this:
int *a = (int*)malloc(sizeof(int));
should I free a when the code is done? Thanks!
I think you have a little misunderstanding related to pointer.
Your title says:
Free uninitialized pointer ...
and your code is
int *a = (int*)malloc(sizeof(int));
The problem with this is that there is no uninitialized pointer in the code. The only pointer in the code is the variable a
and it is initialized by the value returned by malloc
.
Freeing an uninitialized pointer would be bad - example:
int *a; // a is an uninitialized pointer
free(a); // Real bad - don't do this
but since you actually initialize the pointer then - Yes, you must call free when your are done using the object/memory pointer a
points to. It does not matter whether or not the pointed-to object (aka memory) has been assigned a value.
The general rule: For each call of malloc
there must be a call of free
(Exception: If your program terminates, you don't need to call free
)
int *a = malloc(sizeof(*a));
if (a)
{
/* a is now valid; use it: */
*a = 1 + 2 + 3;
printf("The value calculated is %d\n", *a);
}
/* Variable A is done being used; free the memory. */
free(a); /* If a failed to be allocated, it is NULL, and this call is safe. */
Yes. If you successfully malloc something is is correct to free it as well.
int *a = (int *) malloc(sizeof int);
if (a != NULL)
{
/* Do whatever you need to do with a */
free(a);
}
else
{
puts("the malloc function failed to allocate an int");
}
int *a = (int*)malloc(sizeof(int));
should I free a when the code is done?
The question should be
Must I free a when the code is done?
And the answer is YES. A malloc
must be accompanied by a a free
statement.
free(a);