c.lang.correctness.incorrect-use-ato-fn.incorrect-use-ato-fn

profile photo of semgrepsemgrep
Author
182
Download Count*

Avoid the 'ato*()' family of functions. Their use can lead to undefined behavior, integer overflows, and lack of appropriate error handling. Instead prefer the 'strtol*()' family of functions.

Run Locally

Run in CI

Defintion

rules:
  - id: incorrect-use-ato-fn
    pattern-either:
      - pattern: atoi(...)
      - pattern: atol(...)
      - pattern: atoll(...)
    message: Avoid the 'ato*()' family of functions. Their use can lead to undefined
      behavior, integer overflows, and lack of appropriate error handling.
      Instead prefer the 'strtol*()' family of functions.
    metadata:
      references:
        - https://stackoverflow.com/q/38393162
        - https://stackoverflow.com/q/14176123
      category: correctness
      technology:
        - c
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]
    languages:
      - c
    severity: WARNING

Examples

incorrect-use-ato-fn.c

#include <stdlib.h>

int main() {
    const char *buf = "";

    // ruleid:incorrect-use-ato-fn
    int i = atoi(buf);

    // ruleid:incorrect-use-ato-fn
    long j = atol(buf);

    // ruleid:incorrect-use-ato-fn
    long long k = atoll(buf);

    // ok:incorrect-use-ato-fn
    long l = strtol(buf, NULL, 10);

    // ok:incorrect-use-ato-fn
    long long m = strtol(buf, NULL, 10);

    // ok:incorrect-use-ato-fn
    long n = strtoq(buf, NULL, 10);

    return 0;
}