MWATelescope / mwalib

Library to read Murchison Widefield Array (MWA) raw visibilities, voltages and metadata into a common structure
Mozilla Public License 2.0
10 stars 2 forks source link

Null termination not happening in C API #39

Closed robotopia closed 2 years ago

robotopia commented 3 years ago

Some functions which populate char arrays do not place a null byte at the termination of the string. I believe it happens for error_messages in many functions, but below is code to reproduce the effect in mwalib_metafits_get_expected_volt_filename(). It counts as a bug because there's no way for the user of the C interface to know how many chars have actually been written, or where to place the null byte.

// Given voltage files and a metafits file, provide metadata about this VCS observation
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "fitsio.h"
#include "mwalib.h"

#define ERROR_MESSAGE_LEN 1024
#define FILENAME_LEN 1024

int main(int argc, char *argv[])
{
    // Assume that the first file provided is the metafits file, and all others
    // are gpubox files or voltage files. Therefore, we need at least one file provided to main.
    int file_count = argc - 1;

    if (file_count < 1)
    {
        printf("At least one file is needed (if only one, it should be the metafits file).\n");
        // print_usage();
    }

    // Allocate buffer for any error messages
    char *error_message = malloc(ERROR_MESSAGE_LEN * sizeof(char));

    // Allocate buffer for the filename
    char *out_filename_ptr = malloc(FILENAME_LEN * sizeof(char));

    memset(out_filename_ptr, 'a', FILENAME_LEN); // Pre-fill array with 'a's

    // Create context pointers
    MetafitsContext *metafits_context = NULL;

    mwalib_metafits_context_new2(argv[1], &metafits_context, error_message, ERROR_MESSAGE_LEN);

    int retval = mwalib_metafits_get_expected_volt_filename(
        metafits_context,
        3,
        1,
        out_filename_ptr,
        FILENAME_LEN,
        error_message,
        ERROR_MESSAGE_LEN
    );

    // puts(error_message);

    puts(out_filename_ptr);

    return EXIT_SUCCESS;
}

Compile with

cargo build --release
gcc -O3 \
    volt-context-bug.c \
    -o volt-context-bug \
    -I ../include \
    -lm -lpthread -ldl \
    -L../target/release/ \
    -lmwalib