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;
}
Likely, in your C implementation,
int,size_t, andchar *are each 32 bits, four bytes. Whenvalis 1073741824,val * sizeof(char *)overflows and, as it happens, produces zero. Thenmem = 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 bemem = malloc(val * sizeof(char));or, better,mem = malloc(val * sizeof *mem):.