Is it safe to write code like below?
void func(int v[], int size) {
int array_local[size];
for(int i = 0; i < size; i++) array_local[i] = v[i];
/*
Other stuff...
*/
}
Or could I stumble upon some kind of error?
Is it safe to write code like below?
void func(int v[], int size) {
int array_local[size];
for(int i = 0; i < size; i++) array_local[i] = v[i];
/*
Other stuff...
*/
}
Or could I stumble upon some kind of error?
It is safe as long as the caller ensures that v
has at least size
elements, otherwise of course it will cause problems, you don't have to worry about that, because you can't do anything about it anyway.
You also have to be careful not to return array_local
, because it will be deallocated when the function returns, since it's allocated in the function stack frame.
Also, the above code is not necessary to copy the array, you could just
memcpy(array_local, v, size * sizeof(int));
Yeah this is perfectly fine and valid on and above C99
. It is called VLA.
To be on safer side, you should put a check on the value of size
before using it as the number of elements of the array. As you've got the size
defined as int
, you should prohibit passing a value of say -5
to size
.
That said, for the remaining part of the code (as a general suggestion)
v[i]
should not cause in memory overrun.return
statement).This is called a Variable Length Array
, and they only exist in C99. So as long as your compiler supports the -c99
compilation flag, and you are using it, the code is valid.
As for whether or not you should use it, that depends on how large you expect size
to be. With stack allocation, you have no protection against allocating too much memory. If you were to use a dynamic allocator, like malloc
, you could check for a NULL
return value, whereas with a VLA
, you will just blow the stack if you ask for too much. If size
will be small, there is no problem with it.
You can implement same thing in other way using dynamic memory allocation and is safe to be implemented:
void func(int v[], int size) {
int *array_local = (int*)malloc(sizeof(int) * size);
for(int i = 0; i < size; i++) *(array_local + i) = *(v + i);
/*
Other stuff...
*/
}