Question

I am using CppUTEST to test some C code. I have a function foo(int *bar) in C which mallocs some memory, writes to the memory and returns to the C++ code. However, when the function returns to the C++ code, the pointer is still a null pointer.

So this is basically what I want to do

bar() {
    int *result=0;
    foo(result);
    cout << *(result+1) << endl;
}

foo(int *bar) {
   bar=(int *)malloc(sizeof(int)*4);
   *(bar+1)=2;
   *(bar+2)=5;
   return 2;
}

It goes both ways, when I allocate the memory in C++ and pass a pointer which I write to, I just get garbage out.

I was under the impression that heap allocated memory would be writable/readable from anywhere.

Was it helpful?

Solution

Make your function foo return the chunk of memory you allocated:

int *foo() {
   int *bar=(int *)malloc(sizeof(int)*4);
   *(bar+1)=2;
   *(bar+2)=5;
   return bar;
}

and then use the returned value to do you tests. Don't forget to free the memory you used.

void bar() {
    int *result=foo();
    cout << *(result+1) << endl;
    free(result);
}

It's perfectly OK to call malloc and free from C++. Just make sure you don't mix up calls to those functions with the new and delete operators.

OTHER TIPS

Your code has a number of problems that make it unsuitable as a c++ program (memory leaks, malloc instead of new, c-array instead of a c++ array or vector...), but I'll treat is as a learning exersize for pointers.

When you creaete the variable result, it is of a type "pointer to integer". A pointer-to-inteder is an address in memory. When you initialize it to zero (in c++ you should initialized it to nullptr instead), you are giving it a placeholder value. The value zero is not the address of any memory you have allocated.

When you call malloc in foo(), the return value of malloc, which you assign to bar, is the address of the first element of memory that malloc allocated. It is a valid pointer address. Inside foo you initialize the memory correctly, but when you return to bar, the variable result is still initialized to zero. So when you try to access that memory by cout'ing it, you are accessing the memory at address 0+1.

You need to give assign result the address of the memory you have allocated.

You can: - allocate the memory outside of foo (this is better as you can have the calling entity free the memroy. - pass a pointer to the pointer, allowing you to change the value of the pointer, not just the memory that it points to. - have foo return the address of the memory it allocated, and assign that to result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top