using malloc over array

时间秒杀一切 提交于 2019-12-22 06:33:16

问题


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().


回答1:


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.




回答2:


Please any one explain with example, what is the meaning of dynamic although we are specifying the size.

I suspect this was significant before C99. Before C99, you couldn't have dynamically-sized auto arrays:

void somefunc(size_t sz)
{
    char buf[sz];
}

is valid C99 but invalid C89. However, using malloc(), you can specify any value, you don't have to call malloc() with a constant as its argument.

Also, to clear up what other purpose malloc() has: you can't return stack-allocated memory from a function, so if your function needs to return allocated memory, you typically use malloc() (or some other member of the malloc familiy, including realloc() and calloc()) to obtain a block of memory. To understand this, consider the following code:

char *foo()
{
    char buf[13] = "Hello world!";
    return buf;
}

Since buf is a local variable, it's invalidated at the end of its enclosing function - returning it results in undefined behavior. The function above is erroneous. However, a pointer obtained using malloc() remains valid through function calls (until you don't call free() on it):

char *bar()
{
    char *buf = malloc(13);
    strcpy(buf, "Hello World!");
    return buf;
}

This is absolutely valid.




回答3:


I would add that in this particular example, malloc() is very wasteful, as there is more memory allocated for the array than what would appear [due to overhead in malloc] as well as the time it takes to call malloc() and later free() - and there's overhead for the programmer to remember to free it - memory leaks can be quite hard to debug.

Edit: Case in point, your code is missing the free() at the end of main() - may not matter here, but it shows my point quite well.

So small structures (less than 100 bytes) should typically be allocated on the stack. If you have large data structures, it's better to allocate them with malloc (or, if it's the right thing to do, use globals - but this is a sensitive subject).

Clearly, if you don't know the size of something beforehand, and it MAY be very large (kilobytes in size), it is definitely a case of "consider using malloc".

On the other hand, stacks are pretty big these days (for "real computers" at least), so allocating a couple of kilobytes of stack is not a big deal.



来源:https://stackoverflow.com/questions/14013620/using-malloc-over-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!