Is it necessary to use new for dynamic memory allocation? - c

In C, we can input the size of an array (at runtime) from the user by the concept of dynamic memory allocation. But we can also use
int n;
scanf("%d",&n);
int a[n];
So what is the need of using pointers for dynamic memory allocation using new?

What you have shown is called variable length array supported from C99.
Yes based on the input you are allocating memory. What if you want to extend the allocated memory.
Don't you need pointers now? In order to do realloc() . This is one scenario I can think of but we need pointers for dynamic memory allocation.
C doesn't have new so my answer is specific to C which has malloc() and family functions
If you have a function to allocate memory dynamically say
int *alloc_memory()
{
int n;
scanf("%d",&n);
int a[n];
// Fill values to array and do
return a;
}
Now this will lead to undefined behavior as the allocated memory just has scope of the function. Pointers are useful for this purpose
int *alloc_memory()
{
int n;
scanf("%d",&n);
int *p = malloc(sizeof(int) * n);
// Fill values
return p;
}
The point is VLA doesn't provide the flexibility which dynamic memory allocation by pointers provide you.

Variable length array came into existence after C99 standard. Before that, there was no concept for VLA. Please note, moving forward, since C11, this has been changed to an optional feature.
OTOH, dynamic memory allocation using malloc()## and family was there from long back.
That said, the VLA is still an array and usually, an array and a pointer are not the same. Array holds type and size information, while a pointer does not have any size information.
Also, FWIW, the array size can be defined at runtime, but that does not change the scope and lifetime as compared to normal arrays. Just using VLA approach does not change the lifetime of an otherwise automatic array to global or something else.
## There is no new keyword in C. GLIBC provides malloc() and family of APIs to handle dynamic memory allocation.

Using a VLA is conceptually similar to calling alloca to allocate automatic mmory.
A few differences between a Variable Length Array (VLA) and dynamically allocated memory using malloc:
1) The VLA is an automatic variable that will cease to exist when your function returns. Whereas dynamically allocated memory with malloc will exist until free is called or your program exits.
2) For data types other than arrays, such as structs, you probably want allocated with malloc.
3) The VLA is typically stored on the stack (although this is not strictly required by the C99 specification), whereas dynamically allocated memory with malloc is stored on the heap.

You are not doing any "dynamic memory allocation", i.e. allocation of memory with dynamic lifetime. You are using "variable-length arrays" in C99. But it's still a local variable, with "automatic storage duration", which means the variable's lifetime is the scope in which it was declared.

Related

What's the difference between variable length array and dynamic memory allocation?

int a[n];
vs
int * a;
a = malloc(n * sizeof(int));
Could anyone explain pro and cons of both method respectively? (efficiency, security etc)
The main difference is the VLA declaration introduces a new Variably Modified (VM) type and that the object has automatic storage, the malloc() variant has dynamic storage.
The code:
int a[n];
is seen by compiler as:
int T_elems = n;
typedef int T[T_elems];
T a;
As result array a has automatic storage and it is allocated on stack on modern systems. Automatic means that the object's memory is released when leaving the scope were the objects was introduced.
int *b;
{
int a[n];
// `a` is valid
b = a;
}
// resources pointed by `b` are released
On the other hand the second snippet:
int * a = malloc(n * sizeof(int));
Creates a pointer to int and assign an dynamically allocated object to it. The objects resources are valid even though scope of a has ended. The memory is valid until release with free().
int *b;
{
int * a = malloc(n * sizeof(int));
b = a;
}
// resources pointed by `b` are valid!
free(b);
// memory is no longer valid
There is a common misconception that VLA are always allocated on stack.
VLAs can be allocated on heap via pointer to arrays:
int (*a)[n] = malloc(sizeof(int[n]));
Summary:
VLAs (and VM types)
Pros:
simple allotaction of automatic VLAs
"always" succeeds (behavior on failure in undefined by C standard)
allocation is very fast (slightly slower than fixed arrays)
no risk of leaks for automatic VLAs
can have dynamic storage (via pointers to VLA)
very convenient for multidimensional arrays
carry its size thus sizeof a returns n * sizeof int
Cons:
automatic VLAs can easily overflow stack
VM types cannot be defined at file scope (cannot be returned)
VM types cannot be used as struct members
become optional feature since C11
operand of sizeof of VLA type is evaluated
automatic VLAs cannot be resized
Dynamic 1D array.
Pros:
supported by all C standards
can be any size, no stack limit
indicates if allocation is successful, however on modern OS malloc() reserved address space. OS give little guarantee that the memory is reserrved
can be resized with realloc()
Cons:
more verbose syntax
must check if successful
allocations are slower than any stack-based allocations
memory must be released with free() to avoid leaks
do not carry size, one must keep size of array
The same data organized as a table:
Automatic VLA
malloc
Syntax
Simple
More verbose
Behavior on error
Stack overflow
NULL
Error handling
Impossible: behavior on failure is undefined
Must check malloc's return value
Maximal size
Stack size
Heap size (larger than stack)
Speed
Very fast (slightly slower than fixed arrays)
Slower than any stack-based allocation
Deallocation
Automatic; no risk of leaks
Memory must be released with free() to avoid leaks
Array size support
Yes, by sizeof
No, programmer must store explicitly
Can return it?
No
Yes
Can put in struct?
No
Yes
Portability
C99, Became optional feature since C11
Supported by all C standards
Supports resizing?
No
Yes, by realloc
Multi-dimensional
Simple syntax
Possibly confusing syntax
VLAs behave (mostly) like any other auto variable - storage for them will automatically be released when you exit their enclosing scope. Dynamic memory will not be released until you explicitly free it.
VLAs are great when you need some temporary working storage that doesn’t need to be too big or hang around beyond the lifetime of its enclosing function. Like fixed-length local arrays, they cannot be arbitrarily large. Despite the name, variable-length arrays cannot be resized once they are defined - the "variable" in variable-length simply means that their size can be different each time it is instantiated.
You’d use dynamic memory when you don’t know until runtime how much memory you need and the allocated object has to live outside the lifetime of any specific function, or needs to be very large, or needs to be resizable (using realloc).

Defining the size of an array during the execution in C

I would like to know if I can define the size of an array in C, during the execution.
For example, can I do this?
int n,i;
scanf("%d",&n);
int v[n];
for(i=0;i<n;i++){
v[i] = i;
}
If this is possible, when should I use the function malloc for dynamic allocation of memory? I mean, if I can read a value n and allocating an array with n positions, during the execution, why should I use malloc?
You can use a variable to specify the length of an array only if the compiler supports Variable-Length Arrays. These were added to the C99 standard, but are now optional under the C11 standard.
One of the differences is, when you declare an array inside a function, it is allocated on the stack. It is a local to that function, and when the function returns, it is deallocated automatically. malloc, allocates on the heap, and returns a pointer to the starting address of the allocated memory. Unlike the storage on the stack, it is not automatically deallocated, if you return the pointer from the function, you can use it in another function, until you free it.
This can be useful for more info: http://www.programmerinterview.com/index.php/data-structures/difference-between-stack-and-heap/

Why do we need dynamic memory allocation despite we can use variable-length arrays instead?

Why do we need dynamic memory allocation despite we can use variable-length arrays instead?
We can allocate dynamic memory at run-time with a variable length array as:
unsigned int x;
printf("Enter size:");
scanf("%d",&x);
int arr[x];
Also we can allocate memory at run-time by using one of dynamic memory allocation functions as:
unsigned int x,*p;
printf("Enter size:");
scanf("%d",&x);
p = (unsigned int *)malloc(x);
So, In both case we can allocate memory during run-time.So, Why do we need dynamic memory allocation despite we can use variable-length arrays instead?
And what benefits we can get when using one of dynamic memory allocation functions than arrays?
Edit code for passing array:
unsigned int *func(unsigned int *p)
{
*p=10; // any processing on array
return p; // we could return a pointer to an array
}
int main()
{
unsigned int x,*P;
printf("Enter size:");
scanf("%d",&x);
unsigned int arr[x];
p = func(arr);
}
Because it has different use cases.
You use automatic memory when you allocate it in a calling routine and you can pass that memory to callees at will. But you will never be able to return it to a caller.
Imagine a library that would use opaque structures to store data - a kind of OOP in C. The API is likely to have routines with this signature:
void * buildEltOfTypeXX(param1, param2, ...);
to create and initialize the opaque structures. In that case, it is evident that the memory must use dynamic allocation (malloc) and not automatic because you would return a dangling pointer. And with that pattern, the caller will get ownership of the memory and will have to free it when it no longer needs it.
In Variable length array (VLA), when you use int arr[x], even if x is calculated dynamically arr will be stored in stack, which has limited space, this makes it unsafe. Because there are chance you run out of space. So if you know the size you use static array, otherwise you write unsafe code.
And in this condition we need Dynamic memory allocation where memory is stored in heap, 'heap' (large pool of memory) usually refers to the memory that is managed by malloc (C) and new (C++) for dynamic memory allocation.
Otherwise, VLA is easier to use, like in simple coding competition/questions, where you have limited size testcases, if it works then its fine otherwise use dynamic allocation, I won't recommend using it in some high level programming( Operating Systems, Browsers, Libraries, Graphics, Banking Applications) unless you are sure it won't cause problem. Also it may be not be compatible with some compiler.
May be this question will also be helpful.
Because int arr[x], when x is a variable value like in your example, isn't a valid standard C (or C++) code.
At least: this is true (If I'm not wrong) with al standardized version of C++ (C++98, C++03, C++11, C++14) and with the first C stantardization (C89).
Variable length array are allowed in C99 but the following (and current) C11 standard made they an optional feature.
So you can rely in variable length (non allocated) array only if you are using a C99 compliant compiler. Never in C++.
p.s.: sorry for my bad English.

Dynamic Array using const int

This is also a valid code to declare dynamic arrays.
malloc needs pointers, this doesn't. Is this a better method?
printf("enter the size of array")
scanf("%d",&x)
const int size
size = x
int array[size]
It is hard to say if one is better than the other, a better question would be what are the advantages of each, you need to decided based on your requirements but using malloc and using variable length arrays(VLA) are not the same.
There are some major differences.1) A VLA will usually be allocated on the stack although that is an implementation decision, the standard just says there are automatic. The stack is more limited than the the heap which is where a malloc'ed array will go and so you can easily overflow your stack. 2) You need to free a malloc'ed array a VLA is an automatic variable and will not exist outside of the scope it is declared in. 3) VLA is part of the C99 standard and so code using VLA will not be portable.

Is this array static or dynamic?

So I'm studying memory allocation and it said that you can only allocate memory dynamically using malloc(); but isn't this dynamic memory allocation too? it works btw.So I'm a bit confused.
#include<stdio.h>
#include<conio.h>
int main()
{
int integer,cntr;
scanf("%d",&integer);
char words[integer];
for(cntr = 0;cntr < integer - 1;cntr++)
words[cntr] = 'k';
words[cntr] = '\0';
printf("%s",words);
getch();
return(0);
}
That's a variable-length array. The size is indeed dynamic, but in practice it'll generally be allocated on the stack instead of the heap (so don't use it for anything too big).
Depending on your compiler and so on, this will probably end up being a lot faster than allocating heap memory, being nothing but an adjustment of the stack pointer.
Variable-length arrays were introduced in the C99 standard, so bear in mind that you won't be able to use them with very old C compilers (such as MSVC).
The array is an local array, and it will automatically deallocated once the scope({,}) in which it is defined ends.
Technically, the standard does not define where it should be allocated but only defines the characteristics such an array has to offer. The standard does not even mention stack or heap.:
This is static because the array is allocated on the stack and not on the heap.
It's not allocated by the memory manager, it's just reserved on the stack, but nothing more. It ceases to exist (in the sense that using it will provide garbage) as soon as it goes out of scope.
Mind that, since stack is limited, you won't be able to allocate a so big array in this way.

Resources