0

I have a function call

void copy_data(FILE *fin, FILE *fout, int size) {
     char buf[size];
     memset(buf, 0, size);
     fread(buf, sizeof buf, 1, fin);
     fwrite(buf, sizeof buf, 1, fout);

}

Is malloc here necessary, because I read that I need to use malloc when I don't know the size at compile time which I don't know here, but I feel like malloc is not neccesary here.

2 Answers2

4

C99 and later allow variable length arrays (VLA). buf is a variable length array and if the size is small you can use it. For large size (stack size limitations) arrays you need to allocate memory dynamically.

Note that since C11, VLA is made optional.

haccks
  • 104,019
  • 25
  • 176
  • 264
3

No it's not necesssary here provided that you are not going to use large amount of memory. Data related to this function will be allocated on a stack together with other variables (you are putting size elements of type char on the stack). You might, however take these points into consideration. If you want to use heap which is bigger, you would need to use malloc() and then manually free the memory.

EDIT As it has been pointed out, the C11 standard makes Variable Length Arrays optional, so problem of portability of your code also comes accross.

gonczor
  • 3,994
  • 1
  • 21
  • 46