What is the maximum size of a Linux environment variable value?

I don’t think there is a per-environment variable limit on Linux. The total size of all the environment variables put together is limited at execve() time. See “Limits on size of arguments and environment” here for more information.

A process may use setenv() or putenv() to grow the environment beyond the initial space allocated by exec.

Here’s a quick and dirty program that creates a 256 MB environment variable.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
  size_t size = 1 << 28; /* 256 MB */
  char *var;

  var = malloc(size);
  if (var == NULL) {
  perror("malloc");
  return 1;
}

  memset(var, 'X', size);
  var[size - 1] = '\0';
  var[0] = 'A';
  var[1] = '=';

  if (putenv(var) != 0) {
  perror("putenv");
  return 1;
}

  /*  Demonstrate E2BIG failure explained by paxdiablo */
  execl("/bin/true", "true", (char *)NULL);
  perror("execl");


  printf("A=%s\n", getenv("A"));

  return 0;
}

Leave a Comment