cpointersmingwcodeblocks

C pointers understanding


I have ran into an issue that has made me realise I don't know as much about pointers as I thought I did.

test.h

#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED


void getDataAlt(char** dst);

#endif // TEST_H_INCLUDED

test.c

#include "test.h"

void getDataAlt(char** dst) {
    char* tmp = *dst;
    tmp = malloc(sizeof(char) * 50);
    sprintf(tmp, "This is a test.\r\n");
    *dst = tmp;
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include "test.h"

#define enableOther

void getData(char** dst);

int main()
{
    char* anOther;
    getData(&anOther);
    printf("Hello %s\n", anOther);
    free(anOther);
    #ifdef enableOther
    char * anOtherAlt;
    getDataAlt(&anOtherAlt);
    printf("Hello Alt %s\n", anOtherAlt);
    free(anOtherAlt);
    #endif
    return 0;
}

void getData(char** dst) {
    char* tmp = *dst;
    tmp = malloc(sizeof(char) * 50);
    sprintf(tmp, "This is a test.\r\n");
    *dst = tmp;
}

This is my code. I am trying to let the function do the allocating etc. and modify the char* that is passed to it.

The local getData works without issue, the one inside the seperate .h /.c file works up till the point of the free(getDataAlt) and it spits out a "double free" error, and I can't for the life of me figure it out.

Running code blocks 20.03 on windows 11, MingW compiler version 8.1.0

New Screenshots: Build window output (warnings are from formatting in leak.h)

Build options showing -Wall and -Wextra

This is my main.c

This is my test.c

This is my test.h

This is my console output


Solution

  • There's a bug in the leak checker you're using.

    If I run this code (with the leak checker) under valgrind I get the following output:

    ==19372== Memcheck, a memory error detector
    ==19372== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
    ==19372== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
    ==19372== Command: ./main
    ==19372== 
    Hello This is a test.
    
    Hello Alt This is a test.
    
    WARNING:: (main.c:20) Double free detected
    /*========= SUMMARY =========*/
      Total allocations      1  
      Total Free             2  
      Total Memory allocated 50 bytes 
      Total Memory freed     50 bytes 
      Memory Leaked          0 bytes 
    ==19372== 
    ==19372== HEAP SUMMARY:
    ==19372==     in use at exit: 0 bytes in 0 blocks
    ==19372==   total heap usage: 2 allocs, 2 frees, 100 bytes allocated
    ==19372== 
    ==19372== All heap blocks were freed -- no leaks are possible
    ==19372== 
    ==19372== For lists of detected and suppressed errors, rerun with: -s
    ==19372== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
    

    It's clear both from looking at the code and the valgrind output that there's no double-free going on. So the leak checker is buggy.