Is this array static or dynamic? - c

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.

Related

memset and static array declaration vs malloc [duplicate]

I was curious with this:
What is the diference between:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
and:
char Buffer[MAX_BUF];
Case 1: In
char Buffer[MAX_BUF];
Buffer is an array of size MAX_BUF. The allocation technique is called VLA.
Case 2: In
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
Buffer is a pointer which is allocated a memory of size MAX_BUF which is 1000.
and, an array is not the same as a pointer, and C-FAQ has a Very Good collection detailing the reasons.
The major difference, in terms of usability and behaviour are:
(1) is on stack, usually Note, while (2) is on heap, always.
(1) has fixed size once allocated, (2) can be resized.
(1) is allocated when the enclosing function is called and has the block scope OTOH, (2) is allocated memory dynamically, at runtime and the returned memory has a lifetime which extends from the allocation until the deallocation.
(1) allocated memory need not be managed by programmer, while in (2) all malloc()d memory should be free()d. [Courtesy: Giorgi]
Note: Wiki
For example, the GNU C Compiler allocates memory for VLAs on the stack.
I will add a bit info in terms of memory management, in addition to what others said.
1) The main difference is here:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
You need to manage the allocated memory manually, e.g., free Buffer when you are done using it. Forgetting to free it (or freeing it twice) may lead to trouble.
2) With the second case:
char Buffer[MAX_BUF];
You don't need to free anything. It will get destroyed automatically. Hence you avoid the task of handling the memory - which is good.
You should try to evaluate always which approach you need.
Some points.
Since second is allocated on stack, the first approach is taken also when large array needs to be created - since more memory is usually available on the heap.
Also if you create array using second approach for example in the method, the life time of the object will be that method - you will not be able to use that array outside that method. Whereas with dynamic allocation that is not the case.
char* Buffer = malloc(MAX_BUF);
creates a char pointer Buffer, dynamically allocates MAX_BUF bytes of memory via the malloc and makes Buffer point to the start of the allocated space. This memory is allocated on the heap.
char Buffer[MAX_BUF];
creates an array Buffer of size MAX_BUF which can hold a maximum of MAX_BUF characters. Note that you are creating a Variable Length Array (a feature introduced in C99) since MAX_BUF is a variable. This array may be created on the stack.
The most notable difference is scope. The VLA array will only be valid inside the scope where it is declared, while a dynamic array will be available everywhere in the program until you call free().
In practice, VLAs may be faster than dynamic memory, in case the compiler use stack allocation for the VLA. It is however not specified by the C standard where a VLA is allocated.
(A compiler could in theory allocate a VLA on the heap, but then the compiler would also be responsible for the clean-up. I don't think any such solutions exist. Every compiler I've used always declare VLAs on the stack.)
This means that VLAs are unsuitable to hold large amounts of data: you would risk stack overflow. This is not a concern when you are using dynamic memory however.
VLAs don't have the same portability as dynamic arrays, since awfully old compilers don't support VLAs. In theory, new C11 compilers don't have to suport VLAs either, though at this point I know of no compiler has been stupid enough to drop that support.
Comparison/summary:
VLAs should be used when there are small amounts of local data, because they have fast allocation time and automatic clean-up.
Dynamic arrays should be used when there are large amounts of data, to prevent stack overflow.
Dynamic arrays should be used when the data needs to persist after the execution of a function and be available elsewhere in the program.
Dynamic arrays should be used when you have exceptional and/or irrational portability requirements.

C Dynamic Allocation w/Pointers [duplicate]

I was curious with this:
What is the diference between:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
and:
char Buffer[MAX_BUF];
Case 1: In
char Buffer[MAX_BUF];
Buffer is an array of size MAX_BUF. The allocation technique is called VLA.
Case 2: In
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
Buffer is a pointer which is allocated a memory of size MAX_BUF which is 1000.
and, an array is not the same as a pointer, and C-FAQ has a Very Good collection detailing the reasons.
The major difference, in terms of usability and behaviour are:
(1) is on stack, usually Note, while (2) is on heap, always.
(1) has fixed size once allocated, (2) can be resized.
(1) is allocated when the enclosing function is called and has the block scope OTOH, (2) is allocated memory dynamically, at runtime and the returned memory has a lifetime which extends from the allocation until the deallocation.
(1) allocated memory need not be managed by programmer, while in (2) all malloc()d memory should be free()d. [Courtesy: Giorgi]
Note: Wiki
For example, the GNU C Compiler allocates memory for VLAs on the stack.
I will add a bit info in terms of memory management, in addition to what others said.
1) The main difference is here:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
You need to manage the allocated memory manually, e.g., free Buffer when you are done using it. Forgetting to free it (or freeing it twice) may lead to trouble.
2) With the second case:
char Buffer[MAX_BUF];
You don't need to free anything. It will get destroyed automatically. Hence you avoid the task of handling the memory - which is good.
You should try to evaluate always which approach you need.
Some points.
Since second is allocated on stack, the first approach is taken also when large array needs to be created - since more memory is usually available on the heap.
Also if you create array using second approach for example in the method, the life time of the object will be that method - you will not be able to use that array outside that method. Whereas with dynamic allocation that is not the case.
char* Buffer = malloc(MAX_BUF);
creates a char pointer Buffer, dynamically allocates MAX_BUF bytes of memory via the malloc and makes Buffer point to the start of the allocated space. This memory is allocated on the heap.
char Buffer[MAX_BUF];
creates an array Buffer of size MAX_BUF which can hold a maximum of MAX_BUF characters. Note that you are creating a Variable Length Array (a feature introduced in C99) since MAX_BUF is a variable. This array may be created on the stack.
The most notable difference is scope. The VLA array will only be valid inside the scope where it is declared, while a dynamic array will be available everywhere in the program until you call free().
In practice, VLAs may be faster than dynamic memory, in case the compiler use stack allocation for the VLA. It is however not specified by the C standard where a VLA is allocated.
(A compiler could in theory allocate a VLA on the heap, but then the compiler would also be responsible for the clean-up. I don't think any such solutions exist. Every compiler I've used always declare VLAs on the stack.)
This means that VLAs are unsuitable to hold large amounts of data: you would risk stack overflow. This is not a concern when you are using dynamic memory however.
VLAs don't have the same portability as dynamic arrays, since awfully old compilers don't support VLAs. In theory, new C11 compilers don't have to suport VLAs either, though at this point I know of no compiler has been stupid enough to drop that support.
Comparison/summary:
VLAs should be used when there are small amounts of local data, because they have fast allocation time and automatic clean-up.
Dynamic arrays should be used when there are large amounts of data, to prevent stack overflow.
Dynamic arrays should be used when the data needs to persist after the execution of a function and be available elsewhere in the program.
Dynamic arrays should be used when you have exceptional and/or irrational portability requirements.

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.

What's the difference between a VLA and dynamic memory allocation via malloc?

I was curious with this:
What is the diference between:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
and:
char Buffer[MAX_BUF];
Case 1: In
char Buffer[MAX_BUF];
Buffer is an array of size MAX_BUF. The allocation technique is called VLA.
Case 2: In
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
Buffer is a pointer which is allocated a memory of size MAX_BUF which is 1000.
and, an array is not the same as a pointer, and C-FAQ has a Very Good collection detailing the reasons.
The major difference, in terms of usability and behaviour are:
(1) is on stack, usually Note, while (2) is on heap, always.
(1) has fixed size once allocated, (2) can be resized.
(1) is allocated when the enclosing function is called and has the block scope OTOH, (2) is allocated memory dynamically, at runtime and the returned memory has a lifetime which extends from the allocation until the deallocation.
(1) allocated memory need not be managed by programmer, while in (2) all malloc()d memory should be free()d. [Courtesy: Giorgi]
Note: Wiki
For example, the GNU C Compiler allocates memory for VLAs on the stack.
I will add a bit info in terms of memory management, in addition to what others said.
1) The main difference is here:
const int MAX_BUF = 1000;
char* Buffer = malloc(MAX_BUF);
You need to manage the allocated memory manually, e.g., free Buffer when you are done using it. Forgetting to free it (or freeing it twice) may lead to trouble.
2) With the second case:
char Buffer[MAX_BUF];
You don't need to free anything. It will get destroyed automatically. Hence you avoid the task of handling the memory - which is good.
You should try to evaluate always which approach you need.
Some points.
Since second is allocated on stack, the first approach is taken also when large array needs to be created - since more memory is usually available on the heap.
Also if you create array using second approach for example in the method, the life time of the object will be that method - you will not be able to use that array outside that method. Whereas with dynamic allocation that is not the case.
char* Buffer = malloc(MAX_BUF);
creates a char pointer Buffer, dynamically allocates MAX_BUF bytes of memory via the malloc and makes Buffer point to the start of the allocated space. This memory is allocated on the heap.
char Buffer[MAX_BUF];
creates an array Buffer of size MAX_BUF which can hold a maximum of MAX_BUF characters. Note that you are creating a Variable Length Array (a feature introduced in C99) since MAX_BUF is a variable. This array may be created on the stack.
The most notable difference is scope. The VLA array will only be valid inside the scope where it is declared, while a dynamic array will be available everywhere in the program until you call free().
In practice, VLAs may be faster than dynamic memory, in case the compiler use stack allocation for the VLA. It is however not specified by the C standard where a VLA is allocated.
(A compiler could in theory allocate a VLA on the heap, but then the compiler would also be responsible for the clean-up. I don't think any such solutions exist. Every compiler I've used always declare VLAs on the stack.)
This means that VLAs are unsuitable to hold large amounts of data: you would risk stack overflow. This is not a concern when you are using dynamic memory however.
VLAs don't have the same portability as dynamic arrays, since awfully old compilers don't support VLAs. In theory, new C11 compilers don't have to suport VLAs either, though at this point I know of no compiler has been stupid enough to drop that support.
Comparison/summary:
VLAs should be used when there are small amounts of local data, because they have fast allocation time and automatic clean-up.
Dynamic arrays should be used when there are large amounts of data, to prevent stack overflow.
Dynamic arrays should be used when the data needs to persist after the execution of a function and be available elsewhere in the program.
Dynamic arrays should be used when you have exceptional and/or irrational portability requirements.

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.

Resources