Skip to content

malloc Fails Silently in wasi-sdk #518

@khordadi

Description

@khordadi

Description

When running the following C program, different behaviors are observed between wasi-sdk and emscripten. Specifically, wasi-sdk fails to detect unsuccessful memory allocations, leading to an infinite loop.

Reproduction Steps

  1. Compile the following program with wasi-sdk and emscripten:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

int allocate(const uint64_t size) {
    printf("Allocating %llu Bytes\n", size);
    void *mem = malloc(size);
    if (mem == NULL) return 0;
    free(mem);
    return 1;
}

int main() {
    uint64_t upper_bound = 1;
    while (allocate(upper_bound))
        upper_bound *= 2;
    printf("Failed to allocate %llu Bytes\n", upper_bound);
    return 0;
}
  1. Compile and run with wasi-sdk:
/opt/wasi-sdk/bin/clang main.c -o main.wasi-sdk.wasm
wasmtime main.wasi-sdk.wasm

Output (wasi-sdk)

Allocating 1 Bytes
Allocating 2 Bytes
...
Allocating 9223372036854775808 Bytes
Allocating 0 Bytes
Allocating 0 Bytes
Allocating 0 Bytes
... infinite loop ...
  1. Compile and run with emscripten:
emcc main.c -o main.emcc.wasm
wasmtime main.emcc.wasm

Output (emscripten)

Allocating 1 Bytes
Allocating 2 Bytes
...
Allocating 33554432 Bytes
Failed to allocate 33554432 Bytes

Expected Behavior

  • malloc should return NULL when memory allocation fails.
  • The program should terminate gracefully rather than looping indefinitely.

Actual Behavior (wasi-sdk)

  • malloc continues returning non-NULL pointers even for unreasonably large allocations.
  • This causes an infinite loop instead of terminating when allocation fails.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions