Skip to content

Random segfault on model free #11

@ariaghora

Description

@ariaghora
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#define MT_USE_STB_IMAGE
#define MT_USE_STB_IMAGE_WRITE
#define MT_IMPLEMENTATION
#define MT_USE_NEON
#define MT_USE_IM2COL_CONV
#define MT_USE_APPLE_ACCELERATE
#include "../mint/mint.h"
#define MT_ONNX_IMPLEMENTATION
#include "../mint/mint_onnx.h"

int main(int argc, char **argv) {
    mt_tensor *image = mt_tensor_load_image(argv[1]);
    mt_tensor_unsqueeze_inplace(image, 0);
    mt_tensor *image_resized = mt_upsample(image, 0.5, 0.5, 0);

    mt_model *model = mt_onnx_read_file(argv[2]);
    mt_model_set_input(model, "input1", image_resized);
    mt_model_run(model, NULL, NULL);

    mt_tensor *output = mt_model_get_output(model, "output1");
    mt_tensor_squeeze_inplace(output);

    // clip to 0-255, normalize to 0-1 to comply with mt_tensor_save_image
    for (int i = 0; i < output->shape[0]; i++) {
        for (int j = 0; j < output->shape[1]; j++) {
            for (int k = 0; k < output->shape[2]; k++) {
                int idx = i * output->shape[1] * output->shape[2] +
                          j * output->shape[2] + k;
                mt_float val      = output->data[idx];
                output->data[idx] = fmax(0, fmin(255, val)) / 255.0;
            }
        }
    }
    mt_tensor_save_image(output, "output.jpg", 100);

    mt_tensor_free(image);
    mt_tensor_free(image_resized);
    mt_tensor_free(output);

    mt_model_free(model);
    return 0;
}

This:
mt_model_free(model);

randomly causes segfault on mosaic-9.onnx, probably due to illegal free. LLDB run:

mint.h:3273:12
   3270 MTDEF void mt_tensor_free(mt_tensor *t) {
   3271     if (t == NULL)
   3272         return;
-> 3273     if (t->data != NULL)
   3274         free(t->data);
   3275     free(t);
   3276 }

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions