I have created a simple C
library is generated by one .c and one .h file.
// test.c
#include "test.h"
#include "stdlib.h"
void GetArray(int * array)
{
array = (int *) calloc(2, sizeof(int));
array[0] = 0;
array[1] = 1;
}
// test.h
void GetArray(int * array);
I then generated a C++
executable that would link to the C
library and call this function.
// Test.cpp
#include "Test.hpp"
int main(int argc, char *argv[])
{
int * array;
GetArray(array);
delete[] array;
return 0;
}
with header
// Test.hpp
extern "C" {
#include "test.h"
}
For completeness I include the Makefile
CC = gcc
CPP = g++
# ----- C-based library -------
testlib.a: test.o
ar rcs testlib.a test.o
test.o: test.c
$(CC) -c $<
# ------ C++ executable that links to C-based library -----
Test: Test.o testlib.a
$(CPP) Test.o -o $@ testlib.a
Test.o: Test.cpp
$(CPP) -c $<
.PHONY: clean
clean:
rm -f *.o Test testlib.a
I was surprised to see that despite the delete[] array;
call in Test.cpp
, that a valgrind LEAK SUMMARY report showed that 8 bytes of memory are definitely lost.
I alternatively tried to create array
directly in Test.cpp
without the call to the C-library function GetArray
. That is
// Test.cpp
#include "Test.hpp"
int main(int argc, char *argv[])
{
int * array;
array = new int[2];
array[0] = 0;
array[1] = 1;
delete[] array;
return 0;
}
and observed that the valgrind report then showed no memory leaks. I am not sure why I can't clean memory from the C++ executable that was allocated in a function defined in the C-library.
Change this:
To this:
Then invoke as follows:
Otherwise, if you only declare it as
GetArray(int*)
, then the parameter valuearray
will get overwritten, but the caller's value for array is never changed. Remember, even pointers themselves are passed by value.A more natural way of course is this:
Then invoked as: