Botodach
Botodach

Reputation: 11

Assertion failed - load matrix

typedef struct {
    size_t rows;
    size_t cols;
    size_t stride;
    float *es;
} Mat;
Mat t = mat_alloc(img_width*img_height, 3);
Mat mat_alloc(size_t rows, size_t cols)
{
    Mat m;
    m.rows = rows;
    m.cols = cols;
    m.stride = cols;
    m.es = NN_MALLOC(sizeof(*m.es)*rows*cols);
    NN_ASSERT(m.es != NULL);
    return m;
}

NN_ASSERT - assert NN_MALLOC - malloc

const char *out_file_path = "img.txt";
FILE *out = fopen(out_file_path, "w");

mat_save(out, t);

void mat_save(FILE *out, Mat m)
{
    const char *magic = "nn.h.mat";
    fwrite(magic, strlen(magic), 1, out);
    fwrite(&m.rows, sizeof(m.rows), 1, out);
    fwrite(&m.cols, sizeof(m.cols), 1, out);
    for (size_t i = 0; i < m.rows; ++i) {
        size_t n = fwrite(&MAT_AT(m, i, 0), sizeof(*m.es), m.cols, out);
        while (n < m.cols && !ferror(out)) {
            size_t k = fwrite(m.es + n, sizeof(*m.es), m.cols - n, out);
            n += k;
        }
    }
}

#define MAT_AT(m, i, j) (m).es[(i)*(m).stride + (j)]

Just so you know, the code is provided in a scattered manner and is not actually like that! :-)

Changed: Well, so as not to confuse myself and you, I will describe the problem in full

When I save a file using mat_save I get unreadable data and I realized that this is normal, but when I want to load my saved matrix I get an error from the mat_load function:

Assertion failed: magic == 0x74616d2e682e6e6e, file ../Headers/nn.h, line 159

Mat mat_load(FILE *in)
{
    uint64_t magic;
    fread(&magic, sizeof(magic), 1, in);
    NN_ASSERT(magic == 0x74616d2e682e6e6e);
    size_t rows, cols;
    fread(&rows, sizeof(rows), 1, in);
    fread(&cols, sizeof(cols), 1, in);
    Mat m = mat_alloc(rows, cols);

    size_t n = fread(m.es, sizeof(*m.es), rows*cols, in);
    while (n < rows*cols && !ferror(in)) {
        size_t k = fread(m.es, sizeof(*m.es) + n, rows*cols - n, in);
        n += k;
    }

    return m;
}

Upvotes: 1

Views: 70

Answers (0)

Related Questions