Reading an environment variable with getenv()
will not cause a buffer overflow.
On Linux, inherited environment variables and their values are stored in the process address space by the kernel during exec()
. The getenv()
function just returns a pointer to this existing data. Since it does not copy any data, there is no buffer, and there can be no buffer overflow.
If you try to pass too many environment variables to a new process, exec()
will signal the E2BIG
error.
Security concerns
There aren't really any buffer overflow concerns with environment variables.
The security concerns center around the fact that you shouldn't trust the contents of the environment. If your program is run setuid (or setgid, etc.) then the environment is an attack vector. The user can set PATH
or LD_PRELOAD
or other variables in malicious ways.
However, it's rare to write setuid programs. This is a good thing, since there are so many reasons why it's difficult to make setuid programs secure.
getenv
must take care of that itself. – Ellergetenv()
, which is not what most people expect (nor is it common practice in Unix systems for that to be a problem). So, strictly, you need to make a copy of any environment variable returned bygetenv()
before callinggetenv()
again. There isn't a header that directly defines a limit on the size of env var names or values. On POSIX, theARG_MAX
limit (which is often 256 KiB) is the total size of 'environment plus arguments', but that's pretty big and not always a firm limit. – Inguinal