sysbench icon indicating copy to clipboard operation
sysbench copied to clipboard

sb_memory.c:199:18: warning: ‘buffer’ may be used uninitialized in this function [-Wmaybe-uninitialized]

Open deep1712 opened this issue 4 years ago • 1 comments

It can be removed by putting
buffer = NULL; (at \src\tests\memory\sb_memory.c:115)

deep1712 avatar Mar 26 '21 09:03 deep1712


/*
 * sb_memory.c – Sysbench memory test
 */

#include "sbtest.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

static void *buffer = NULL;
static size_t bufsize = 0;
static size_t mem_block_size = 0;
static int read_only = 0;

void sb_mem_init(size_t block_size, size_t size, int ro)
{
    mem_block_size = block_size;
    bufsize = size;
    read_only = ro;

    if (buffer)
        free(buffer);

    buffer = (void *)malloc(bufsize);
    if (!buffer) {
        fprintf(stderr, "Failed to allocate %zu bytes\n", bufsize);
        exit(EXIT_FAILURE);
    }
}

void sb_mem_run(void)
{
    volatile char *ptr = (volatile char *)buffer;

    for (size_t i = 0; i < bufsize; i += mem_block_size) {
        if (!read_only)
            memset((void *)(ptr + i), 0xFF, mem_block_size);
        else
            (void)*(ptr + i);
    }
}

void sb_mem_free(void)
{
    if (buffer) {
        free(buffer);
        buffer = NULL;  /* ✅ Prevent double free / invalid reuse */
    }
}

/* Simple standalone test */
#ifdef TEST_MEMORY_MAIN
int main(void)
{
    printf("Allocating...\n");
    sb_mem_init(4096, 1024 * 1024, 0);

    printf("Running write test...\n");
    sb_mem_run();

    printf("Freeing...\n");
    sb_mem_free();

    printf("Re-freeing (should be safe)...\n");
    sb_mem_free();  // double free safe now

    printf("All done.\n");
    return 0;
}
#endif

ljluestc avatar Oct 12 '25 17:10 ljluestc