Does freeing an uninitialized pointer result in undefined behavior? - c

If you have a pointer that is not initialized and, by mistake, try to free it, is this going to result in undefined behavior?
Like:
int main(void){
char *string;
free(string);
return 0;
}

Does freeing an uninitialized pointer result in undefined behavior?
Yes.
However, freeing a null pointer is well-defined.
From the C99 standard:
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or
realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

Yes, because accessing any uninitialised variable provokes undefined behaviour.
This includes passing an uninitialise pointer tofree(). This itself also includes the case where the uninitialise pointer "by accident" may have a value equal to NULL.

Yes, it is undefined behavior.
The pointer passed to free should be a pointer to a valid object allocated with malloc, calloc, realloc or a null pointer.
From C99:
(7.20.3.2p2) "If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc, malloc, or realloc function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined."

Yes, it does, since you should only free() a pointer that 1. is NULL or 2. you obtained via a call to malloc(), calloc() or realloc().

Related

Why is it okay to call free with null pointer?

It's clear from the C standards that NULL is an acceptable input to free(), with the result being no operation performed. However, this seems to violate the idea that free() must only be called on memory that was explicitly allocated using malloc(), calloc(), or realloc().
What's the reasoning behind this exception? The only reason I can figure is so that callers do not have to explicitly check for NULL before calling free().
The malloc function (as well as calloc and realloc) may return a NULL pointer if the requested size is 0. Therefore, it makes sense that NULL pointer can also be passed to free since it was returned from a successful call to malloc:
Section 7.22.3p1 of the C standard specifies this behavior:
If the space cannot be allocated, a null pointer is returned. If the
size of the space requested is zero, the behavior is
implementation-defined: either a null pointer is returned, or the
behavior is as if the size were some nonzero value, except
that the returned pointer shall not be used to access an object.

Confusion about realloc function

I read about dynamic memory allocation in C using this reference.
That document Say's :
realloc() should only be used for dynamically allocated memory. If the
memory is not dynamically allocated, then behavior is undefined.
If we use realloc() something like this:
int main()
{
int *ptr;
int *ptr_new = (int *)realloc(ptr, sizeof(int));
return 0;
}
According to that reference, this program is undefined because pointer ptr not allocated dynamically.
But, If I use something like:
int main()
{
int *ptr = NULL;
int *ptr_new = (int *)realloc(ptr, sizeof(int));
return 0;
}
Is it also undefined behavior according to that reference?
I thing second case does not invoked undefined behaviour. Am I right?
The first case has undefined behavior, and the second doesn't. In the first case, the value of ptr is indeterminate. So passing that value to realloc or any function, is undefined by itself.
On the other hand, since realloc has well defined behavior when passed a null pointer value (it's just like calling malloc)1, the second piece of code is perfectly legitimate (other than the fact you don't free anything).
1 7.22.3.5 The realloc function / p3
If ptr is a null pointer, the realloc function behaves like the malloc function for the specified size.
In the first case the program almost sure will finish by segmentation fault as the linked lists that are created in the heap to find segments are not coherent, in the second case you call the realloc with the NULL first parameter, which means, is a call equivalent to malloc(size)
man realloc says:
void *malloc(size_t size);
void *realloc(void *ptr, size_t size);
If ptr is NULL, then the call is equivalent to malloc(size), for all values of size
The only authorative reference is the standard document. n1570 (the latest C11 standard) has the following to say:
ยง7.22.3.5 The realloc function, p3:
If ptr is a null pointer, the realloc function behaves like the malloc function for the
specified size. Otherwise, if ptr does not match a pointer earlier returned by a memory
management function, or if the space has been deallocated by a call to the free or
realloc function, the behavior is undefined. [...]
So, your second example is well-defined.
The first case is obviously undefined behavior because we don't know where the ptr is pointing or what the ptr is holding at that time. And c standard says that 7.20.3.4.2 The realloc function
The realloc function deallocates the old object pointed to by ptr and
returns a pointer to a new object that has the size specified by size.
So first case is Undefined behavior.
In second case compiler knows what ptr has so it is valid but realloc()
will act as malloc() according to 7.20.3.4.3 The realloc function
If ptr is a null pointer, the realloc function behaves like the
malloc function for the specified size.

2 Ways of calling free - is there a difference?

Is there a difference between those two variants of calling free after allocating memory on the heap:
// variant 1
int* p1 = (int*) malloc(sizeof(int)*4);
free(p1);
//variant 2
int* p2 = (int*) malloc(sizeof(int)*4);
free(*p2);
*p2 = NULL;
Yes, there is a difference.
Variant 2 is invalid. free expects a pointer previously returned by malloc, calloc, or realloc. *p2 is the first int in the allocated space, though. As man free says, undefined behavior occurs therefore (quotation adjusted for this specific case):
free() function frees the memory space pointed to by [p1], which must have been returned by a previous call to malloc(), calloc(), or realloc(). Otherwise, [...] undefined behavior occurs.
Notes:
don't cast the result of malloc
Yes. free(*p2) is invalid.
free frees the memory at the address it's given. Consider: what does p1 evaluate to? Its value is the pointer that malloc returned - so p1 evaluates to the pointer to the memory that malloc allocated.
What does *p2 evaluate to? Its value is the integer that is stored at the address of p2. This can be anything and it is very unlikely it'll be a valid pointer. Thus free will attempt to free an invalid memory address and you'll get a segfault if you're lucky.
Yes, there's a difference. The first way, called on a pointer pointing to memory allocated by malloc is right. The second, calling a dereference of such a pointer, attempts to free some arbitrary memory address (with the value held in the value that pointer is pointing to), and is just wrong.
free(p1);
This is valid as you allocate memory to p1 and then free, thus no problem.
free(*p2);
It is unlikely to be valid as *p2 may or may not be a valid pointer (which need to have an allocated memoty ).
using free() on a pointer which is not allcocated memory using malloc or similar will cause error.

C realloc() function fails

Why does this code not work?
char *x=malloc(100);
x++;
x=realloc(x, 200);
I mean x is a valid string pointer, just incremented by one?
See C Standard (C99, 7.20.3.4p3) on realloc and my emphasis:
void *realloc(void *ptr, size_t size);
If ptr is a null pointer, the realloc function behaves like the malloc function for the
specified size. Otherwise, if ptr does not match a pointer earlier returned by the
calloc, malloc, or realloc function, or if the space has been deallocated by a call
to the free or realloc function, the behavior is undefined.
In your case x was returned by malloc, not x + 1. So your program invokes undefined behavior.
Think about what realloc does. How can it free the pointer at address x+1 when malloc actually created a pointer at address x?
In more concrete terms, let's assume you allocated 100 bytes at address 0x1000. Now x is incremented, pointing at 0x1001. Then you call realloc at the new address. Because none of malloc, calloc, and realloc created 0x1001, free (or equivalent code) used by the call to realloc has no idea how to do anything with 0x1001; it can't even fathom how many bytes of memory it occupies. It only knows about the 100 bytes at 0x1000.
The basic idea behind implementations of malloc and friends is that you keep track of the pointers assigned and how many bytes were allocated. Then when free is called later, the pointer passed to free is looked up. If there is no reference to that pointer passed to free, what else is there to do except crash? That, to me, is more logical than supposing you can keep using a pointer that may or may not be valid.
char *x=malloc(100);
x++;
x=realloc(x, 200);
In the code shown above the address pointed by the pointer x is changed before invoking the realloc() function. This is undefined behavior in C.
This is an undefined behavior as you if you think that you have obtained a pointer from malloc() which is wrong.
Clearly x was returned by malloc and its value was changed before calling realloc() Hence it is showing the undefined behavior.

Dynamic memory allocation in C

i just experiment the things on the c language
could you answer my question regarding the program i've written
void main()
{
char *p,; // created a pointer pointing to string
p = (char *) malloc(50); // dynamically create 50 bytes.
strcpy(p, "this code is written about the dynamic allocation");
p += 20;
free(p);
}
Now could anyone tell me what is the effect of free(p) statement will the last 30 bytes will be freed of and used for the future memory allocation.? what would be the output?
You are not supposed to free any addresses but those returned by malloc(), calloc() or realloc(). And p + 20 is no such address.
http://codepad.org/FMr3dvnq shows you that such a free() is likely to fail.
The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
Does the pointer passed to free() have to point to beginning of the memory block, or can it point to the interior? is also worth reading.
Even if you could use free() on any pointer that points to a malloc'd memory - your could would free it twice since you are calling free() on more than one memory inside that area. And double-frees are evil as they can result in security holes.
It will result in Undefined Behavior.
The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation. If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by the calloc(), malloc(), posix_memalign(), realloc(), strdup() function, or if the space has been deallocated by a call to free() or realloc(), the behavior is undefined.

Resources