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
  • 3
    Umm.. where is the malloc? Commented Jan 8, 2018 at 14:40
  • 1
    I am not using the malloc here because I think I can create array just like this? That's why I am asking if I should be using malloc here. Commented Jan 8, 2018 at 14:41

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It is not an extension, it is an optional feature and gcc supports it.
@JensGustedt; The thing is GCC supports VLA in C90 as an extension and I thought it is also an extension for C99 an later.
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.

1 Comment

@SergeBallesta thanks for mentioning it. I've made an update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.