'How to address the Valgrind invalid read / write of size 1 & Address # is 0 bytes after a block of size x alloc'd in C

I see this Valgrind issue of invalid read / write of size 1 & Address # is 0 bytes after a block of size x alloc'd is quite commonplace and I am unable to quite pinpoint in my context.

For some background, I am making a dynamic string encoding function:

I declare a calloc'd buffer as so: char * buffer = calloc( 4, sizeof(char) );

I declare another variable that will hold the building encoding string as: char * encoded_str = calloc(5, sizeof(char));

The string sequence of the buffer and the returned encoded string should be 3 and 4 chars respectively. I have alloc'd a one character padding each per the plethora of posts concerning this topic, such as:

Valgrind: Invalid read / write of size 1

I imagined that zero-terminating all my strings would be the move but it is not resolving the issue.

Proceeding onward:

I read 3 bytes of a file into the buffer as so: fread( buffer, sizeof(char), 3, in_file );

and I similarly null-terminate it: buffer[3] = '\0';

I have the desire to call my encoder function on buffer with the expectation that it will be stored in encoded_str as such: encoded_str = encoder( buffer );

However, I have a memory leak as:

==77225== HEAP SUMMARY:
==77225==     in use at exit: 5 bytes in 1 blocks
==77225==   total heap usage: 4 allocs, 3 frees, 582 bytes allocated

==74372== 5 bytes in 1 blocks are definitely lost in loss record 1 of 1
==74372==    at 0x4C2C089: calloc (vg_replace_malloc.c:762)
==74372==    by 0x400C78: sendToEncoder (enc.c:139)

where line 139 corresponds to the char * encoded_str = calloc(5, sizeof(char));

This encoded_str is the return product of the function and I null terminate after this call for consistency sake.

The output is correct where the input is literally just "fo".

There is a lot more complexity but the fact that the program is erroring in this most basic of cases tells me there is some basic aspect of memory allocation / management that I am missing that is propagating as the clauses get more complex and encoded_str builds.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source