Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using malloc over array

May be similar question found on SO. But, I didn't found that, here is the scenario

Case 1

void main()
{
    char g[10];
    char a[10];
    scanf("%[^\n] %[^\n]",a,g);
    swap(a,g);
    printf("%s %s",a,g);
}

Case 2

void main()
{
    char *g=malloc(sizeof(char)*10);
    char *a=malloc(sizeof(char)*10);
    scanf("%[^\n] %[^\n]",a,g);
    swap(a,g);
    printf("%s %s",a,g);
}

I'm getting same output in both case. So, my question is when should I prefer malloc() instead of array or vice-verse and why ?? I found common definition, malloc() provides dynamic allocation. So, it is the only difference between them ?? Please any one explain with example, what is the meaning of dynamic although we are specifying the size in malloc().

like image 207
Ravi Avatar asked Dec 23 '12 18:12

Ravi


1 Answers

The principle difference relates to when and how you decide the array length. Using fixed length arrays forces you to decide your array length at compile time. In contrast using malloc allows you to decide the array length at runtime.

In particular, deciding at runtime allows you to base the decision on user input, on information not known at the time you compile. For example, you may allocate the array to be a size big enough to fit the actual data input by the user. If you use fixed length arrays, you have to decide at compile time an upper bound, and then force that limitation onto the user.

Another more subtle issue is that allocating very large fixed length arrays as local variables can lead to stack overflow runtime errors. And for that reason, you sometimes prefer to allocate such arrays dynamically using malloc.

like image 101
David Heffernan Avatar answered Sep 27 '22 22:09

David Heffernan