Reputation: 395
I'm wondering if it is okay to use the strcpy()
function in C to copy a heap array to a stack array? Are there any potential problems to that?
Upvotes: 2
Views: 934
Reputation: 3907
Of course it's okay to copy into a stack array.
To be clear, it would look like this:
char on_stack[100];
strcpy(on_stack, source_string_on_heap);
Just make sure that the stack array is big enough to hold what you're copying, and be aware that the stack array will disappear after its context ends. Never have a function return a pointer to a stack variable.
Note on strcpy()
usage: Your source buffer must be null-terminated and your destination buffer must have room for the termination character as well. This has nothing to do with heap or stack usage, it's just how the strcpy()
function works.
You are also free to use any other method to copy from the heap to the stack, including using memcpy()
or manually copying byte-by-byte with a char*
and loop.
Upvotes: 5
Reputation: 24857
No, it is not OK:
1) Unless you can be sure that the source array is null-terminated, the copy may run out-of-bounds: UB.
2) If the source array contains data with embedded nulls, the copy will terminate before all the required data is copied.
3) There is no limit on strcpy() that can be used to prevent overrunning the destination buffer if its end is reached before the null-terminator is found in the source: UB.
Upvotes: 2