'Can't use "/usr/bin/env" in C execve() call on macOS

I couldn't really find any relevant results after looking for a while, so I'm asking this myself. I have the following C code, which tries to execute nasm through execve() via /usr/bin/env so I don't have to hardcode the path to the executable.

#include <unistd.h>
int main(int argc, char**argv) {
    char *cmds[10] = {"/usr/bin/env", "nasm", "--version", NULL};
    execve(cmds[0], cmds, NULL);
}

On linux (Ubuntu 18/20), it works fine:

linux $ gcc test.c && ./a.out
NASM version 2.13.02
linux $

However, on macOS (Catalina, at least), I get the following:

macos $ gcc test.c && ./a.out                                                                                                                            
env: nasm: No such file or directory
macos $

I'm not exactly sure what the difference is. I do have NASM installed, I can run nasm --version on my terminal just fine. It also works fine if I hardcode the path /usr/local/bin/nasm to the execve() call. If I try to run the following manually on my terminal, it also seems to work:

macos $ /usr/bin/env nasm --version
NASM version 2.15.05 compiled on Aug 29 2020
macos $

The reason I want to use /usr/bin/env is that the default install location for nasm is different for different OSs, and I don't want to just hardcode the paths.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source