Incorrect Use Ato Fn Critical

The functions atoi(), atol() and atoll() do not allow specifying the numeric base or checking for conversion errors. If the input string is invalid or out of the supported range, they invoke undefined behavior instead of returning an error. Strtol() and its variants strtoll() and strtoull() are safer alternatives as they allow specifying the base and return a pointer to the next unparsed character. This pointer can be checked against the original string to ensure the entire string was parsed.

Detector ID
c/incorrect-use-ato-fn@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5const char *buf = "";
6void incorrectUseAtoFnNonCompliant()
7{
8    // Noncompliant: Insecure function used
9    int i = atoi(buf);
10    printf("Converted integer: %d\n", i);
11}

Compliant example

1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5char* endptr;
6const char *buf = "";
7int incorrectUseAtoFnCompliant()
8{
9    // Compliant: secure function used
10    long num = strtol(buf, &endptr, 10);
11    if(endptr == buf) {
12        printf("Conversion failed\n");
13        return 1;
14    }
15    printf("Converted number: %ld\n", num);
16    return 0;
17}