How can I mitigate integer overflow in this code?

497 views Asked by At

When I input "1073741824", it returns "Segmentation fault".

"1073741824" is 4294967296÷4, which is (INT_MAX+1)÷(sizeof(char *)).

and also, this is the malloc()'s parameter in this code.

But I don't know how to mitigate this problem.

Help me please.

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

int main(int argc, char **argv)
{
    int val, i;
    char *mem;

    if (argc < 2)
        exit(1);

    val = atoi(argv[1]);

   if (val > 0) {
        mem = malloc(val * sizeof(char *));

      if (mem == NULL) {
          printf("Failure\n");
          exit(2);
      }
    }

    for (i = 0; i < val; i++) {
        mem[i] = 'A';
        printf("%c", mem[i]);
    }

    printf("\n");

    return 0;
}
1

There are 1 answers

2
Eric Postpischil On BEST ANSWER

Likely, in your C implementation, int, size_t, and char * are each 32 bits, four bytes. When val is 1073741824, val * sizeof(char *) overflows and, as it happens, produces zero. Then mem = malloc(val * sizeof(char *)); allocates zero bytes of memory. It returns a valid pointer to zero bytes, not NULL, so your test for NULL does not cause your program to exit.

Then your program attempts to write 1073741824 bytes into the allocated memory. Since zero bytes were allocated, it overruns the space and crashes.

mem = malloc(val * sizeof(char *)); should be mem = malloc(val * sizeof(char)); or, better, mem = malloc(val * sizeof *mem):.