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.
Related
Normally, realloc() is used to reallocate a previously allocated pointer:
int *DynamicArray = malloc(sizeof(int)*SomeArbitraryValue);
// Some rando code where DynamicArray is used
DynamicArray = realloc(DynamicArray, sizeof(int)*SomeOtherArbitraryValue)
But can realloc() be used to directly allocate memory? As in
int *DynamicArray = realloc(/*...*/);
Can realloc() handle non-preallocated pointers?
Yes, just pass NULL to it's first argument.
The manpage of realloc(3) says ...
The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. 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). Unless ptr is NULL, it must have been returned by an
earlier call to malloc(), calloc(), or realloc(). If the area pointed to was moved, a free(ptr) is done.
As the answer by #ZhangBoyang tells you, yes, assuming one possible interpretation of your question. However the way you've worded your question ("non-preallocated pointers") suggests you may have misunderstanding of some of the concepts involved. malloc does not "allocate pointers". It allocates objects, and pointers are values that point to objects. The lifetime of those objects are not connected to the lifetime of any particular pointer pointing to them.
Passing a pointer to realloc doesn't "do anything to" the pointer. It does something to the object pointed to by it. If the pointer is uninitialized or invalid, the call has undefined behavior and bad things will happen. If the pointer is a null pointer, however, realloc(ptr, n) will behave exactly as malloc(n).
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().
If I allocate memory to pointers in a loop successively, does the compiler consider it as a single instance? Concretely:
for (i = 0; i < SOME_VAL; i++)
{
char *p = NULL;
p = malloc(sizeof(char));
SEND_POINTER_ON_NETWORK(p);
}
Will the compiler at every execution create a new instance of p or will it continue allocating memory to p? I am using VS2010.
char *p = NULL;
p = malloc(sizeof(char));
Each call to malloc() within the loop allocates new memory location to the pointer p , if you are trying to extend the already allocated memory to p then use realloc().
The memory management system looks for a free memory slot at the size of the argument in malloc (in this case sizeof(char)). You do not free the memory from one iteration to the next. Therefore, the memory management system 'sees' the memory as occupied and allocates a new memory slot to pointer p.
You have a memory leak in your code.
From ISO/IEC 9899:
(known as c99 standard)
7.20.3.3 The malloc function
Synopsis
1 #include <stdlib.h>
void *malloc(size_t size);
Description
2 The malloc function allocates space for an object whose size is specified by size and
whose value is indeterminate.
Returns
3 The malloc function returns either a null pointer or a pointer to the allocated space.
The behaving you expect would be made by realloc, which is described as follows:
7.20.3.4 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 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. 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.
Also notable is the fact, that MSVC compiler isn't strict conform to the standard in all topics.
But in the both cited cases I know they are conform with it. So it is also valid for your question.
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.
This question already has answers here:
What's the point of malloc(0)?
(17 answers)
Closed 8 years ago.
What does malloc(0) return?
Would the answer be same for realloc(malloc(0),0)?
#include<stdio.h>
#include<malloc.h>
int main()
{
printf("%p\n", malloc(0));
printf("%p\n", realloc(malloc(0), 0));
return 0;
}
Output from Linux GCC:
manav#manav-workstation:~$ gcc -Wall mal.c
manav#manav-workstation:~$ ./a.out
0x9363008
(nil)
manav#manav-workstation:~$
The output keep changing everytime for malloc(0). Is this a standard answer? And why would anyone be interested in getting such a pointer, other than academic research?
EDIT:
If malloc(0) returns dummy pointer, then how does following works:
int main()
{
void *ptr = malloc(0);
printf("%p\n", realloc(ptr, 1024));
return 0;
}
EDIT:
The following code outputs "possible" for every iteration. Why should it not fail ?
#include<stdio.h>
#include<malloc.h>
int main()
{
int i;
void *ptr;
printf("Testing using BRUTE FORCE\n");
for (i=0; i<65000; i++)
{
ptr = malloc(0);
if (ptr == realloc(ptr, 1024))
printf("Iteration %d: possible\n", i);
else
{
printf("Failed for iteration %d\n", i);
break;
}
}
return 0;
}
Others have answered how malloc(0) works. I will answer one of the questions that you asked that hasn't been answered yet (I think). The question is about realloc(malloc(0), 0):
What does malloc(0) return? Would the answer be same for realloc(malloc(0),0)?
The standard says this about realloc(ptr, size):
if ptr is NULL, it behaves like malloc(size),
otherwise (ptr is not NULL), it deallocates the old object pointer to by ptr and returns a pointer to a new allocated buffer. But if size is 0, C89 says that the effect is equivalent to free(ptr). Interestingly, I can't find that statement in C99 draft (n1256 or n1336). In C89, the only sensible value to return in that case would be NULL.
So, there are two cases:
malloc(0) returns NULL on an implementation. Then your realloc() call is equivalent to realloc(NULL, 0). That is equivalent to malloc(0) from above (and that is NULL in this case).
malloc(0) returns non-NULL. Then, the call is equivalent to free(malloc(0)). In this case, malloc(0) and realloc(malloc(0), 0) are not equivalent.
Note that there is an interesting case here: in the second case, when malloc(0) returns non-NULL on success, it may still return NULL to indicate failure. This will result in a call like: realloc(NULL, 0), which would be equivalent to malloc(0), which may or may not return NULL.
I am not sure if the omission in C99 is an oversight or if it means that in C99, realloc(ptr, 0) for non-NULL ptr is not equivalent to free(ptr). I just tried this with gcc -std=c99, and the above is equivalent to free(ptr).
Edit: I think I understand what your confusion is:
Let's look at a snippet from your example code:
ptr = malloc(0);
if (ptr == realloc(ptr, 1024))
The above is not the same as malloc(0) == realloc(malloc(0), 1024). In the second, the malloc() call is made twice, whereas in the first, you're passing a previously allocated pointer to realloc().
Let's analyze the first code first. Assuming malloc(0) doesn't return NULL on success, ptr has a valid value. When you do realloc(ptr, 1024), realloc() basically gives you a new buffer that has the size 1024, and the ptr becomes invalid. A conforming implementation may return the same address as the one already in ptr. So, your if condition may return true. (Note, however, looking at the value of ptr after realloc(ptr, 1024) may be undefined behavior.)
Now the question you ask: malloc(0) == realloc(malloc(0), 1024). In this case, let's assume that both the malloc(0) on the LHS and RHS returns non-NULL. Then, they are guaranteed to be different. Also, the return value from malloc() on the LHS hasn't been free()d yet, so any other malloc(), calloc(), or realloc() may not return that value. This means that if you wrote your condition as:
if (malloc(0) == realloc(malloc(0), 1024)
puts("possible");
you won't see possible on the output (unless both malloc() and realloc() fail and return NULL).
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
void *p1;
void *p2;
p1 = malloc(0);
p2 = realloc(p1, 1024);
if (p1 == p2)
puts("possible, OK");
/* Ignore the memory leaks */
if (malloc(0) == realloc(malloc(0), 1024))
puts("shouldn't happen, something is wrong");
return 0;
}
On OS X, my code didn't output anything when I ran it. On Linux, it prints possible, OK.
malloc(0) is Implementation Defined as far as C99 is concerned.
From C99 [Section 7.20.3]
The order and contiguity of storage allocated by successive calls to the calloc,
malloc, and realloc functions is unspecified. The pointer returned if the allocation
succeeds is suitably aligned so that it may be assigned to a pointer to any type of object
and then used to access such an object or an array of such objects in the space allocated
(until the space is explicitly deallocated). The lifetime of an allocated object extends
from the allocation until the deallocation. Each such allocation shall yield a pointer to an
object disjoint from any other object. The pointer returned points to the start (lowest byte
address) of the allocated space. 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.
In C89, malloc(0) is implementation dependent - I don't know if C99 has fixed this or not. In C++, using:
char * p = new char[0];
is well defined - you get a valid, non-null pointer. Of course, you can't use the pointer to access what it points to without invoking undefined behaviour.
As to why this exists, it is convenient for some algorithms, and means you don't need to litter your code with tests for zero values.
C99 standard
If the space cannot be allocated, a
nullpointer 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.
The comp.lang.c FAQ has the following to say:
The ANSI/ISO Standard says that it may
do either; the behavior is
implementation-defined (see question
11.33). Portable code must either take care not to call malloc(0), or be
prepared for the possibility of a null
return.
So, it's probably best to avoid using malloc(0).
One point nobody cared to talk about yet, in your first program is that realloc with length 0 is the same thing as free.
from the Solaris man page:
The realloc() function changes the size of the block pointed
to by ptr to size bytes and returns a pointer to the (possibly moved) block. The contents will be unchanged up to the
lesser of the new and old sizes. If ptr is NULL, realloc()
behaves like malloc() for the specified size. If size is 0
and ptr is not a null pointer, the space pointed to is made
available for further allocation by the application, though
not returned to the system. Memory is returned to the system
only upon termination of the application.
If one doesn't know that it can be a source of bad surprise (happened to me).
See C99, section 7.20.3:
If the size of the space requested is
zero, the behavior is
implementationdefined: 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.
This is valid for all three allocation functions (ie calloc(), malloc() and realloc()).
I think it depends.
I checked the Visual Studio 2005 sources and saw this in the _heap_alloc function:
if (size == 0)
size = 1;
I think that in many cases you may want a valid pointer, even when asking for zero bytes.
This is because this consistent behavior makes it easier to check your pointers because: if you have a non-NULL pointer it's OK; if you have a NULL pointer you probably have a problem.
That's why I think that most implementations will return a valid pointer, even when asking for zero bytes.
If malloc(0) returns dummy pointer, then how does following works:
void *ptr = malloc(0);
printf("%p\n", realloc(ptr, 1024));
I don't know what you mean by "dummy pointer". If malloc(0) returns non-NULL, then ptr is a valid pointer to a memory block of size zero. The malloc implementation saves this information in an implementation-specific way. realloc knows the (implementation-specific) way to figure out that ptr points to a memory block of size zero.
(How malloc/realloc/free do this is implementation-specific. One possibility is to allocate 4 bytes more than requested and store the size just before the memory block. In that case, ((int *)ptr)[-1] would give the memory block size, which is 0. You should never do this from your code, it's only for use by realloc and free).