atoi Used for Size and Memory Allocation Calculations
Using atoi to parse size parameters for memory allocation without validating the result or checking for overflow conditions.
A medium-severity security vulnerability where C code uses atoi, atol, or atoll functions that lack error reporting and can overflow or misparse input, yielding undefined behavior and incorrect values. These functions can't distinguish between legitimate zero values and parsing errors, and they don't detect integer overflow conditions. When these incorrect values propagate into logic, size computations, or security checks, they can enable buffer overflows, logic bypass, authentication bypass, or information disclosure attacks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// VULNERABLE: atoi for buffer size without validation
void allocate_buffer(const char* size_str) {
int size = atoi(size_str); // Returns 0 on error!
char* buffer = malloc(size);
if (!buffer) {
return;
}
strcpy(buffer, "data");
printf("Buffer: %s\n", buffer);
free(buffer);
}#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>
// SECURE: strtol with validation
void allocate_buffer(const char* size_str) {
char* endptr;
errno = 0;
long size_long = strtol(size_str, &endptr, 10);
// Check for parsing errors
if (errno == ERANGE || size_long < 1 || size_long > INT_MAX) {
printf("Invalid size\n");
return;
}
// Check entire string was consumed
if (endptr == size_str || *endptr != '\0') {
printf("Invalid format\n");
return;
}
int size = (int)size_long;
char* buffer = malloc(size);
if (!buffer) {
return;
}
strcpy(buffer, "data");
printf("Buffer: %s\n", buffer);
free(buffer);
}The vulnerable code uses atoi() which returns 0 on parse errors, leading to malloc(0) and potential buffer overflow. The secure version uses strtol() with proper error checking via errno, validates the range, and ensures the entire string was consumed.
Using atoi to parse size parameters for memory allocation without validating the result or checking for overflow conditions.
Sourcery automatically identifies information disclosure from undefined integer conversions via atoi family in c and many other security issues in your codebase.