Dynamic Array using const int - c

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.

Related

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.

Is it necessary to use new for dynamic memory allocation?

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.

Static memory allocation of array at compile time

How compiler determine the size of below array at compile time?
int n;
scanf("%d",&n);
int a[n];
How it is different from dynamic allocation(other than memory is allocated in heap for dynamic array).
If possible please, explain this in terms of activation stack memory image how this array is allocated memory.
The array's size isn't determined at compile time; it's determined at run time. At the time that the array is allocated, n has a known value. In typical implementations where automatic variables are allocated on the program stack, the stack pointer will be adjusted to make room for that many ints. It becomes parts of the stack frame and will be automatically reclaimed when it goes out of scope.
This code was not valid in C90; C90 required that all variables be declared at the beginning of the block, so mixing declarations and code like this was not permitted. Variable-length arrays and mixed code and declarations were introduced in C99.
In C the proper name for the allocation type is automatic. In computing jargon the term stack is sometimes used synonymously.
The storage of a is valid from the point of definition int a[n]; up until the end of the enclosing scope (i.e. the end of the current function, or earlier).
It is just the same as int a[50]; , except that a different number of ints than 50 may be allocated.
A drawback of using automatic arrays (with or without runtime sizes) is that there is no portable way to protect against stack overflow. (Actually, stack overflow from automatic variables is something the C standard does not address at all, but it is a real problem in practice).
If you were to use dynamic allocation (i.e. malloc and friends) then it will let you know if there is insufficient memory by returning NULL, whereas stack overflows are nasty.

malloced array VS. variable-length-array [duplicate]

This question already has answers here:
What's the difference between a VLA and dynamic memory allocation via malloc?
(4 answers)
Closed 6 years ago.
There are two ways to allocate memory to an array, of which the size is unknown at the beginning. The most common way is using malloc like this
int * array;
... // when we know the size
array = malloc(size*sizeof(int));
But it's valid too in C99 to define the array after we know the size.
... // when we know the size
int array[size];
Are they absolutely the same?
No they're not absolutely the same. While both let you store the same number and type of objects, keep in mind that:
You can free() a malloced array, but you can't free() a variable length array (although it goes out of scope and ceases to exist once the enclosing block is left). In technical jargon, they have different storage duration: allocated for malloc versus automatic for variable length arrays.
Although C has no concept of a stack, many implementation allocate a variable length array from the stack, while malloc allocates from the heap. This is an issue on stack-limited systems, e.g. many embedded operating systems, where the stack size is on the order of kB, while the heap is much larger.
It is also easier to test for a failed allocation with malloc than with a variable length array.
malloced memory can be changed in size with realloc(), while VLAs can't (more precisely only by executing the block again with a different array dimension--which loses the previous contents).
A hosted C89 implementation only supports malloc().
A hosted C11 implementation may not support variable length arrays (it then must define __STDC_NO_VLA__ as the integer 1 according to C11 6.10.8.3).
Everything else I have missed :-)

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