Skip to content

Missing malloc NULL checks in C code #81

Description

@bradduthie

Files: src/utilities.c, src/resource.c, src/observation.c, src/game.c, src/landscape.c

Affected locations (not exhaustive):

File Lines
src/utilities.c 67
src/resource.c 414, 520, 522, 537, 539, 541, 555, 587, 589, 607, 609
src/observation.c 599, 616, 619, 639, 641, 643, 659, 661, 675, 677, 804, 806, 1002, 1005, 1020, 1022, 1024, 1031, 1033
src/landscape.c 134, 149, 150, 151, 153
src/game.c 380, 381, 573–586

Description: Throughout the C code, malloc is called without checking whether it returns NULL. For example, in src/utilities.c:

sarray = (int *) malloc(length * sizeof(int));
// No check that sarray != NULL before dereferencing

On modern systems with adequate memory, malloc failure is rare, but it can happen under memory pressure, in constrained environments, or when processing very large arrays. If malloc returns NULL, the subsequent pointer dereference causes a segfault, crashing the R session and losing all unsaved work.

Why it matters: A segfault in an R package is a hard crash — no error message, no opportunity for tryCatch, no way to save the workspace. This is especially problematic in simulation-intensive workflows where a user might be running a long GMSE simulation. R packages distributed via CRAN are expected to handle allocation failures gracefully.

How to fix: After every malloc call, check the return value and call error() if it is NULL:

sarray = (int *) malloc(length * sizeof(int));
if(sarray == NULL){
    error("Memory allocation failed in find_descending_order");
}

R's error() function will safely unwind the C stack and return control to the R interpreter, producing a proper error message instead of a segfault.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

To doThings to do to improve GMSE

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions