Is this macro safe or should I make sure alloca never returns NULL?
#define DO_COPY(x) strcpy(alloca(strlen((x)) + 1), x)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If the string is user controlled I’d say that alloca is not safe. The way alloca is implemented in many compilers it doesn’t do any kind of sanity checking on the amount it subtracts from (or adds to if your stack grows that way) the stack pointer. Even with large red zones around the stack it would be relatively easy to make the alloca():ed string to point way outside the stack.
Especially in a threaded environment the thread stacks can be quite small and close to each other.
On the linux machines I could test this on it would require a 10MB string to do start scribbling on some other threads stack with this. On MacOS 512kB seems to be enough.
Here’s a quick hack to see how close you can end up (notice that this doesn’t really tell you much if the stack allocation is done using some randomizing allocator like in OpenBSD or some other system that takes their allocator safety seriously).
And here is what strcpy(alloca(strlen(s) + 1), s) gets compiled to:
Notice how there’s no sanity checking other than quick alignment before subtracting the return value from strlen (in %rax) from the stack pointer.