Suppose I've two code samples for creating a integer array of 10 elements:
int *pi = (int*)0;
realloc(pi,10);
and the other is the one that is written normally, i.e.:
int *pi;
pi= malloc(10*sizeof(int));
Now, my question is: The first type of assignment is legal but not used. Why, although there I may get the starting location of my choice?
Initialization of pointers with constants are legal but not used. Why?
malloc() is a function which is used to allocate a block of memory dynamically. 2. calloc() is a function which is used to allocate multiple blocks of memory. 2.
Functions malloc, calloc, realloc and free are used to allocate /deallocate memory on heap in C/C++ language. These functions should be used with great caution to avoid memory leaks and dangling pointers.
If you need to keep your data, use realloc(). It's ~4 times faster than using malloc()/free() and copying your data when scaling up. When scaling down it is 10,000-100,000 times faster.
Many compilers simplify their code by having one memory allocation function. calloc and realloc and maybe malloc usually will call the same memory allocator. HOWEVER, there is nothing in the standard that says that calloc and realloc must call malloc .
When NULL
is passed, realloc
is equivalent to malloc
. The NULL
call can be useful if you're re allocating in some kind of loop and don't want to have a special case the first time you allocate.
While we're at it, the fairly standard ways to use malloc and realloc are:
int* p;
p = malloc(10 * sizeof(int)); //Note that there's no cast
//(also, it could just be int* p = malloc(...);)
int* np = realloc(p, 15 * sizeof(int));
//Note that you keep the old pointer -- this is in case the realloc fails
As a tangential aside: history is the main reason you see declarations and assignments on different lines. In older versions of C, declarations had to come first in functions. That meant that even if your function didn't use a variable until 20 lines in, you had to declare at the top.
Since you typically don't know what the value of a variable not used for another 20 lines should be, you can't always initialize it to anything meaningful, and thus you're left with a declaration and no assignment at the top of your function.
In C99/C11, you do not have to declare variables at the top of scopes. In fact, it's generally suggested to define variables as close to their use as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With