1

Coming back to some C code I wrote a few years ago and I feel it ought to be leaking memory, but I can find no sign that is it and I would like to check my assumptions.

I have a structure like this:

struct BitArray { .... char *bits; .... } 

bits is allocated dynamically like this:

bArray->bits = (char *)calloc(1, 1 << shiftNumber); 

And free-ed like this:

free(nextBA->bits); 

But shouldn't that leak memory - ie it will only free the very first char that bits points to? What is the correct way to free the memory allocated in this way?

1 Answer 1

6

No it won't leak memory. In fact this is all good.

You are passing something that is earlier passed by memory management function (calloc here). So it's ok.

From standard 7.22.3.1 the caution

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by a memory management function, or if the space has been deallocated by a call to free or realloc, the behavior is undefined.

Well here this is certainly not the case. So it's alright.

it will only free the very first char that bits points to?

No it will free the allocated chunk.

The way you have done is the right way.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, been writing too much C++ lately :-)
What's writing in C++ got to do with it? If you use calloc() and free() in C++ in this way, the same answer applies.
Because modern C++ is all about passing references and not about new/delete

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.