What address malloc and calloc returns? - heap-memory

Is the malloc or calloc returns pointer which specifies the exact location of data to be stored?

See here
The malloc() and calloc() functions return a pointer to the allocated
memory, which is suitably aligned for any built-in type. On error,
these functions return NULL. NULL may also be returned by a
successful call to malloc() with a size of zero, or by a successful
call to calloc() with nmemb or size equal to zero.
It returns an address which is valid in the current process.

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.

What if NULL and size 0 are passed to realloc()?

Is the behavior implementation defined? If NULL and size == 0 are passed to realloc():
int main(void)
{
int *ptr = NULL;
ptr = realloc(ptr, 0);
if(ptr == NULL)
{
printf("realloc fails.\n");
goto Exit;
}
printf("Happy Scenario.\n");
Exit:
printf("Inside goto.\n");
return 0;
}
The above code should print "realloc fails", right? But it is not? I've read somewhere that this call to realloc may return NULL also. When does that happen?
This behavior is implementation defined.
From the C standard:
Section 7.22.3.5 (realloc):
3 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. If
memory for the new object cannot be allocated, the old object is
not deallocated and its value is unchanged.
So realloc(NULL, 0) is the same as malloc(0)
If we then look at section 7.22.3.4 (malloc):
2 The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.
3 The malloc function returns either a null pointer or a pointer to the allocated space.
The standard does not state what happens when 0 is passed in.
But if you look at the Linux man page:
The malloc() function allocates size bytes and returns a pointer to
the allocated memory. The memory is not initialized. If size is 0,
then malloc() returns either NULL, or a unique pointer value that can
later be successfully passed to free().
It explicitly states that the returned value can be freed but is not necessarily NULL.
In contrast, MSDN says:
If size is 0, malloc allocates a zero-length item in the heap and
returns a valid pointer to that item. Always check the return from
malloc, even if the amount of memory requested is small.
So for MSVC, you won't get a NULL pointer.
realloc(3) doc:
If ptr is NULL, then the call is equivalent to malloc(size), for all values of size
malloc(3) doc:
If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be success‐fully passed to free().
So yes, it is implementation defined, you'll either get null or a pointer you can free.
The call
realloc(NULL, size);
is equivalent to
malloc(size);
And what malloc() does when asked to allocate 0 bytes is a bit unclear, the standard doesn't say. I think it's implementation-defined. It basically "doesn't matter"; either it returns NULL, or it returns a pointer where you can legally access zero bytes, those are pretty much alike. Both can be passed to free().

Freeing allocated memory: realloc() vs. free()

so I have a piece of memory allocated with malloc() and changed later with realloc().
At some point in my code I want to empty it, by this I mean essentially give it memory of 0. Something which would intuitively be done with realloc(pointer,0). I have read on here that this is implementation defined and should not be used.
Should I instead use free(), and then do another malloc()?
It depends on what you mean: if you want to empty the memory used, but still have access to that memory, then you use memset(pointer, 0, mem_size);, to re-initialize the said memory to zeroes.
If you no longer need that memory, then you simply call free(pointer);, which'll free the memory, so it can be used elsewhere.
Using realloc(pointer, 0) may work like free on your system, but this is not standard behaviour. realloc(ptr, 0) is not specified by the C99 or C11 standards to be the equivalent of free(ptr).
realloc(pointer, 0) is not equivalent to free(pointer).
The standard (C99, §7.22.3.5):
The realloc function
Synopsis
1
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
Description
2 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. The contents of the new
object shall be the same as that of the old object prior to deallocation, up to the lesser of
the new and old sizes. Any bytes in the new object beyond the size of the old object have
indeterminate values.
3 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. If memory for the new object cannot be
allocated, the old object is not deallocated and its value is unchanged.
Returns
4
The realloc function returns a pointer to the new object (which may have the same
value as a pointer to the old object), or a null pointer if the new object could not be
allocated.
As you can see, it doesn't specify a special case for realloc calls where the size is 0. Instead, it only states that a NULL pointer is returned on failure to allocate memory, and a pointer in all other cases. A pointer that points to 0 bytes would, then, be a viable option.
To quote a related question:
More intuitively, realloc is "conceptually equivalent" to to malloc+memcpy+free on the other pointer, and malloc-ing a 0-byte chunk of memory returns either NULL either a unique pointer, not to be used for storing anything (you asked for 0 bytes), but still to be freeed. So, no, don't use realloc like that, it may work on some implementations (namely, Linux) but it's certainly not guaranteed.
As another answer on that linked question states, the behaviour of realloc(ptr, 0) is explicitly defined as implementation defined according to the current C11 standard:
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
realloc() is used to increase or decrease the memory and not to free the memory.
Check this, and use free() to release the memory (link).
I don't think you mean "empty"; that would mean "set it to some particular value that I consider to be empty" (often all bits zero). You mean free, or de-allocate.
The manual page says:
If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr).
Traditionally you could use realloc(ptr, 0); as a synonym for free(ptr);, just as you can use realloc(NULL, size); as a synonym for malloc(size);. I wouldn't recommend it though, it's a bit confusing and not the way people expect it to be used.
However, nowadays in modern C the definition has changed: now realloc(ptr, 0); will free the old memory, but it's not well-defined what will be done next: it's implementation-defined.
So: don't do this: use free() to de-allocate memory, and let realloc() be used only for changing the size to something non-zero.
Use free() to free, to release dynamically allocated memory.
Although former documentations state that realloc(p, 0) is equivalent to free(p), the lastest POSIX documentation explictly states that this is not the case:
Previous versions explicitly permitted a call to realloc (p, 0) to free the space pointed to by p and return a null pointer. While this behavior could be interpreted as permitted by this version of the standard, the C language committee have indicated that this interpretation is incorrect.
And more over:
Applications should assume that if realloc() returns a null pointer, the space pointed to by p has not been freed.
Use free(pointer); pointer = 0 instead of realloc(pointer, 0).
void* realloc (void* ptr, size_t size);
In C90 :
if size is zero, the memory previously allocated at ptr is deallocated as if a call to free was made, and a null pointer is returned.
In C99:
If size is zero, the return value depends on the particular library implementation: it may either be a null pointer or some other location that shall not be dereferenced.
I would use realloc to give a pointer more or less memory, but not to empty it. To empty the pointer I would use free.

Is the pointer calloc function return a pointer vector? (C language)

I'm trying to understand a c code, (SimpleScalar, bpred.c), there is the thing that confuses me a lot:
int *shiftregs;
shiftregs = calloc(1, sizeof(int));
int l1index, l2index;
l1index = 0;
l2index = shiftregs[l1index];
I delete some code that might not help. After the calloc call, *shiftregs becomes a pointer array? And what is the value of l2index? Thanks a lot!
Since shiftregs is a pointer to an int, *shiftregs is an int.
Since calloc guarantees that the memory it allocates is set to 0, and you've allocated enough memory to refer to shiftregs[0], l2index will be 0 (assuming calloc didn't fail and return NULL).
The calloc() function is being used to allocate a dynamic array of zeroed integers that can be referenced via the pointer shiftregs.
The value in l2index is going to be zero unless the allocation failed (calloc() returned NULL). If the allocation failed, you invoke undefined behaviour; anything could happen, but your program will probably crash. Check the allocation so that it doesn't crash!
l2index is 0. calloc set memory to zero. Following is Linux Programmer's Manual:
calloc() allocates memory for an array of nmemb elements of size
bytes each and returns a pointer to the allocated memory. The memory
is set to zero. If nmemb or size is 0, then calloc() returns
either NULL, or a unique pointer value that can later be successfully
passed to free().
Check if the calloc() return NULL.
If so, the "l2index = shiftregs[l1index];"will crash, for you try to get value from a NULL point(shiftregs).
If not, as they said l2index will be 0.

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.

Resources