valgrind leak error after deletion of all dynamic memory - c++

I have tried to learn CPP pointer as well as to free all the memory about which I have used valgrind. But unfortunately I am getting leak error and I don't know where I am making the mistake. Also not so much idea about finding error as a human-readable way from valgrind. Any guidance to find the leak is highly appreciable.
compiler: g++ (Ubuntu 7.5.0-3ubuntu1~16.04) 7.5.0
related info regarding snippet
smart pointer is not used intentionally
it is a minimal example code. So, some portion might seem to be unnecessary.
file.cpp
#include <iostream>
void algo_fun(unsigned int* ip_ptr_array_,
unsigned int ip_size_,
unsigned int** op_ptr_array_,
unsigned int* op_size_)
{
*(op_size_) = ip_size_ + 2;
// following approach is good as it allocate dynamic memory
unsigned int* local = new unsigned int[*(op_size_)];
for (unsigned int i = 0; i< *(op_size_); i++)
{
local[i]=i+1*3;
}
*op_ptr_array_ = &local[0];
local[3] = 87;
}
int main()
{
// input array's contetnt
unsigned int ip_size = 10;
unsigned int* ip_ptr_array = new unsigned int[ip_size];
// output data
unsigned int op_size;
unsigned int* op_ptr_array;
// filling input array
for(unsigned int i = 0; i < ip_size; i++)
{
ip_ptr_array[i] = i+2*2;
}
// function calling to get output data
algo_fun(ip_ptr_array,
ip_size,
&op_ptr_array,
&op_size);
delete [] ip_ptr_array;
delete [] op_ptr_array;
return 0;
}
Working version will be found here.
command used to test: valgrind --leak-check=full --show-leak-kinds=all -v ./file
Leak Summary from valgrind
==23138== LEAK SUMMARY:
==23138== definitely lost: 0 bytes in 0 blocks
==23138== indirectly lost: 0 bytes in 0 blocks
==23138== possibly lost: 0 bytes in 0 blocks
==23138== still reachable: 72,704 bytes in 1 blocks
==23138== suppressed: 0 bytes in 0 blocks
==23138==
==23138== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
==23138== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

tl;dr Please check that you are using a recent Valgrind.
With a combination of Valgrind and gdb you should be able to see what is going on.
I get the following (FreeBSD 12.2, g++ 10.3.0, Valgrind built from git HEAD, [OS and compiler version are not relevant]). I'm using the --trace-malloc=yes option to see all the mallloc/free calls. Don't do that on a large application.
$ valgrind --leak-check=full --trace-malloc=yes ./test
--61886-- malloc(72704) = 0x5800040
--61886-- calloc(1984,1) = 0x5811C80
--61886-- calloc(104,1) = 0x5812480
--61886-- calloc(224,1) = 0x5812530
--61886-- calloc(80,1) = 0x5812650
--61886-- calloc(520,1) = 0x58126E0
--61886-- calloc(88,1) = 0x5812930
--61886-- _Znam(40) = 0x58129D0
--61886-- _Znam(48) = 0x5812A40
--61886-- _ZdaPv(0x58129D0)
--61886-- _ZdaPv(0x5812A40)
--61886-- free(0x5800040)
==61886==
==61886== HEAP SUMMARY:
==61886== in use at exit: 3,000 bytes in 6 blocks
==61886== total heap usage: 9 allocs, 3 frees, 75,792 bytes allocated
_Znam is the mangled version of array new and _ZdaPv the mangled version of array delete from your code. The other calls to malloc/calloc/free come from libc/libstc++. You will probably see different traces on Linux or with libc++.
You could use --show-reachable=yes to get information on the reachable memory.
If I now run under gdb.
$ gdb ./test
(gdb) b malloc
(gdb) b malloc
(gdb) r
Breakpoint 1, malloc (nbytes=96) at /usr/src/libexec/rtld-elf/rtld.c:5877
This is a call to malloc in the link loader, ld.so. I then executed several more 'r's until
Breakpoint 1, __je_malloc_initialized () at jemalloc_jemalloc.c:208
Here the link loader has loaded libstdc++.so and global malloc has been replaced by jemalloc.
Getting the callstack
(gdb) bt
#0 __je_malloc_initialized () at jemalloc_jemalloc.c:208
#1 imalloc (sopts=<optimized out>, dopts=<optimized out>) at jemalloc_jemalloc.c:1990
#2 __malloc (size=72704) at jemalloc_jemalloc.c:2042
#3 0x00000008006eb6f4 in ?? () from /usr/local/lib/gcc10/libstdc++.so.6
#4 0x000000080060e2fd in objlist_call_init (list=<optimized out>, lockstate=<optimized out>) at /usr/src/libexec/rtld-elf/rtld.c:2820
#5 0x000000080060d03d in _rtld (sp=0x7fffffffe408, exit_proc=0x7fffffffe3d0, objp=0x7fffffffe3d8) at /usr/src/libexec/rtld-elf/rtld.c:811
#6 0x000000080060a8c9 in rtld_start () at /usr/src/libexec/rtld-elf/amd64/rtld_start.S:39
#7 0x0000000000000000 in ?? ()
(gdb)
Note the same allocation size on line #2.
I'm not going to dig into what this memory is for, something part of the C++ runtime.
libstdc++ (and libc) deliberately do not free this memory (presumably this is either difficult or just not worth it). In order to filter out these allocations, Valgrind uses a special function to ask libstc++/libc to free this memory.
The option in this case is
--run-cxx-freeres=no|yes free up libstdc++ memory at exit on Linux
(strictly speaking, not just Linux).
Looking at the Valgrind release notes
Release 3.12.0 (20 October 2016)
...
* New option --run-cxx-freeres=<yes|no> can be used to change whether
__gnu_cxx::__freeres() cleanup function is called or not. Default is
'yes'.
So I presume that you are using version 3.11 or earlier.
Finally, if I use clang++/libc++ there is no runtime allocation (and also no freeres function).

Related

C++ memory leak. Valgrind - mismatched delete

I receive objects from Thread #1 - its a 3rd party lib code - my callback called on it.
Objects have fixed-length string fields wrapped:
typedef struct somestr_t {
char * Data;
int Len; } somestr_t;
I have to create copy of the objects by hand every time, before I can pass it further to my code. So amongst other things I copy these strings too using this helper:
inline void CopyStr(somestr_t * dest, somestr_t * src)
{
if (src->Len == 0) {
dest->Len = 0;
return;
}
char* data = new char[src->Len];
memcpy(data, src->Data, src->Len);
dest->Data = data;
dest->Len = src->Len;
}
Then somewhere down the road I delete the object and its string fields:
if (someobj != nullptr)
{
if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data;
. . .
delete someobj ;
}
When I run valgrind I get these in places where I would expect the strings to be deleted:
==33332== Mismatched free() / delete / delete []
==33332== at 0x48478DD: operator delete(void*, unsigned long) (vg_replace_malloc.c:935)
==33332== by 0x41B517: cleanup() (Recorder.cpp:86)
==33332== by 0x41BB29: signal_callback(int) (Recorder.cpp:129)
==33332== by 0x4C11DAF: ??? (in /usr/lib64/libc.so.6)
==33332== by 0x4CD14D4: clock_nanosleep##GLIBC_2.17 (clock_nanosleep.c:48)
==33332== by 0x4CD6086: nanosleep (nanosleep.c:25)
==33332== by 0x4D02DE8: usleep (usleep.c:32)
==33332== by 0x41C3EF: Logger(void*) (LogThreads.h:28)
==33332== by 0x4C5C6C9: start_thread (pthread_create.c:443)
==33332== by 0x4BFC2B3: clone (clone.S:100)
==33332== Address 0xd661260 is 0 bytes inside a block of size 12 alloc'd
==33332== at 0x484622F: operator new[](unsigned long) (vg_replace_malloc.c:640)
==33332== by 0x419E72: CopyStr (CbOverrides.h:23)
and summary report:
==34077== HEAP SUMMARY:
==34077== in use at exit: 328,520 bytes in 3,828 blocks
==34077== total heap usage: 124,774 allocs, 120,946 frees, 559,945,294 bytes allocated
==34077==
==34077== LEAK SUMMARY:
==34077== definitely lost: 0 bytes in 0 blocks
==34077== indirectly lost: 0 bytes in 0 blocks
==34077== possibly lost: 0 bytes in 0 blocks
==34077== still reachable: 328,520 bytes in 3,828 blocks
==34077== suppressed: 0 bytes in 0 blocks
I never used valgrind (or any c++ tool) before so I am not sure - why mismatch delete is reported? why there are 328K unreleased memory on exit?
char* data = new char[src->Len];
and
if (someobj ->somestr.Len != 0) delete someobj ->somestr.Data;
That delete should be delete [].
Why are there still reachable: 425,333 bytes in 3,860 blocks. Sorry, my crystal ball isn't working.
Normally Valgrind does give a hint as to what you need to do
==19283== Rerun with --leak-check=full to see details of leaked memory
It's a little bit mean in that after you've done that it will tell you about another option
==21816== Reachable blocks (those to which a pointer was found) are not shown.
==21816== To see them, rerun with: --leak-check=full --show-leak-kinds=all
Try those and start working through the non-freed memory.

throw() with clang++ shows possible memory leak

I have a piece of code, which when compiled with g++ does not show any memory leaks.
Whereas, the same when compiled with clang++ shows, possible memory leak.
Here's the trace,
==7115==
==7115== HEAP SUMMARY:
==7115== in use at exit: 16 bytes in 1 blocks
==7115== total heap usage: 2,324 allocs, 2,323 frees, 2,166,060 bytes allocated
==7115==
==7115== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==7115== at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==7115== by 0x4129830: __cxxabiv1::__calloc_with_fallback(unsigned long, unsigned long) (in /opt/xxx/lib64/libc++abi.so.1)
==7115== by 0x4128946: __cxa_get_globals (in /opt/xxx/lib64/libc++abi.so.1)
==7115== by 0x412B287: __cxa_throw (in /opt/xxx/lib64/libc++abi.so.1)
==7115== by 0x4E712AE: Lib::GenCmd::RaiseException(Status, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >) (LibBase.cpp:291)
==7115==
==7115== LEAK SUMMARY:
==7115== definitely lost: 0 bytes in 0 blocks
==7115== indirectly lost: 0 bytes in 0 blocks
==7115== possibly lost: 0 bytes in 0 blocks
==7115== still reachable: 16 bytes in 1 blocks
==7115== suppressed: 0 bytes in 0 blocks
==7115==
==7115== For counts of detected and suppressed errors, rerun with: -v
Well, its not possible to share the code snippet, but I can tell you RaiseException() is the function where I have a call made to throw() (at line 291) an exception. Here's the function snippet:
void GenCmd::RaiseException(Status status, std::string AdditionalMsg) throw(Status) {
s_last_error = GetStatusString(status);
if (false == AdditionalMsg.empty()) {
s_last_error = s_last_error + AdditionalMsg;
}
throw(status);
}
Status is a structure, defined as below (along with default, parameterized & copy constructors)
typedef struct _Status {
const u64_t m_status : 8;
const u64_t ReservedByte1 : 8;
const u64_t m_action : 8;
const u64_t ReservedByte3 : 5;
const u64_t m_testbit1 : 1;
const u64_t m_testbit2 : 1;
const u64_t m_cmd_failure : 1;
const u64_t m_module_code : 4;
const u64_t m_file_code : 8;
const u64_t ReservedByte7 : 4;
const u64_t m_line_no : 16;
}Status
The fact, that no leaks are seen with GCC, but only with Clang makes me think this to be some issue with Clang. (With Clang, I mean it could be libcxxabi as well)
I was navigating through the source for clang, & __cxa_get_globals() is the function where a calloc() call is made. I am not yet sure of the execution flow for clang.
Any idea or any inputs which could confirm this to be a Clang issue & not my code issue?
Here's the clang version I am using. The code is compiled with C++11, additionally with '-stdlib=libc++, '-lc++', '-lc++abi'.
[user~]$ clang --version
clang version 7.1.0
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/bin
Update: This exception is raised from the constructor.
Update
I wrote another dummy code to see the behaviour with Clang, & it seems the issue is actually with the Clang (libc++abi).
Have a look at the below naive code
#include <iostream>
#include <stdexcept>
class Positive {
int m_number1;
public:
Positive() : m_number1(10) {
}
Positive(int no) {
if (no < 0) {
// throw 100;
throw std::invalid_argument("Send positive nu");
} else {
m_number1 = no;
}
}
~Positive() {
}
void print() {
std::cout<< "Value of member is: " <<m_number1 <<std::endl;
}
};
int main() {
try {
Positive p1;
p1.print();
Positive p2(100);
p2.print();
Positive p3(-10);
p3.print();
} catch(...) {
std::cout << "Some Exception occured" <<std::endl;
}
return 0;
}
Even on executing the above code, I saw the same result on Valgrind. Here's the output:
[user]$ valgrind --leak-check=full --leak-resolution=high --show-leak-kinds=all ./a.out
==119789== Memcheck, a memory error detector
==119789== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==119789== Using Valgrind-3.14.0 and LibVEX; rerun with -h for copyright info
==119789== Command: ./a.out
==119789==
Value of member is: 10
Value of member is: 100
Some Exception occured
==119789==
==119789== HEAP SUMMARY:
==119789== in use at exit: 16 bytes in 1 blocks
==119789== total heap usage: 3 allocs, 2 frees, 201 bytes allocated
==119789==
==119789== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==119789== at 0x4C2BFB9: calloc (vg_replace_malloc.c:762)
==119789== by 0x40FF830: __cxxabiv1::__calloc_with_fallback(unsigned long, unsigned long) (in /usr/local/lib/libc++abi.so.1.0)
==119789== by 0x40FE946: __cxa_get_globals (in /usr/local/lib/libc++abi.so.1.0)
==119789== by 0x4101287: __cxa_throw (in /usr/local/lib/libc++abi.so.1.0)
==119789== by 0x4014B0: Positive::Positive(int) (in /home/user/test/a.out)
==119789== by 0x4010F9: main (in /home/user/test/a.out)
==119789==
==119789== LEAK SUMMARY:
==119789== definitely lost: 0 bytes in 0 blocks
==119789== indirectly lost: 0 bytes in 0 blocks
==119789== possibly lost: 0 bytes in 0 blocks
==119789== still reachable: 16 bytes in 1 blocks
==119789== suppressed: 0 bytes in 0 blocks
==119789==
==119789== For counts of detected and suppressed errors, rerun with: -v
==119789== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
[user]$
Interestingly, it shows 3 allocations made. Which I am assuming to be something related to the 3rd object, but how can I ensure that is cleared (or not allocated itself)?
Probably, the same thing can help me fix my original code.
I also found this problem. It actually occurs if your code throws anything at least once, so the simplest reproduction scenario is just running this code:
int
main()
{
try {
throw 42;
} catch (int) {}
}
However, if you throw several times there is still just one 16-bytes "leaked" block (which is not really leaked, since it is still reachable from some global variable). Digging into libc++abi library sources shows that such blocks are actually allocated once per thread to hold some exception processing context, and each one is freed when a thread is destroyed since it uses TLS and have proper destructor registered. So after all, it looks totally safe and is not an issue.

Memory leak detected by valgrind, but cannot find line where I forget to free [duplicate]

This question already has answers here:
PRE-2016 Valgrind: Memory still reachable with trivial program using <iostream>
(3 answers)
Closed 6 years ago.
Here is simplified version of the code, I deleted everything that doesn't concern the problem.
#include <iostream>
#define N 3
int main() {
int *input;
int **cl;
input = new int[N];
cl = new int*[N];
for(int i = 0; i < N; i++) {
cl[i] = new int[N];
}
for(int i = 0; i < N; i++) {
delete[] cl[i];
}
delete[] cl;
delete[] input;
return 0;
}
And the valgrind output:
==5782== HEAP SUMMARY:
==5782== in use at exit: 72,704 bytes in 1 blocks
==5782== total heap usage: 6 allocs, 5 frees, 72,776 bytes allocated
==5782==
==5782== 72,704 bytes in 1 blocks are still reachable in loss record 1 of 1
==5782== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==5782== by 0x4EC3EFF: ??? (in /usr/lib/x86_64-linux-gnu/libstdc++.so.6.0.21)
==5782== by 0x40104E9: call_init.part.0 (dl-init.c:72)
==5782== by 0x40105FA: call_init (dl-init.c:30)
==5782== by 0x40105FA: _dl_init (dl-init.c:120)
==5782== by 0x4000CF9: ??? (in /lib/x86_64-linux-gnu/ld-2.23.so)
==5782==
==5782== LEAK SUMMARY:
==5782== definitely lost: 0 bytes in 0 blocks
==5782== indirectly lost: 0 bytes in 0 blocks
==5782== possibly lost: 0 bytes in 0 blocks
==5782== still reachable: 72,704 bytes in 1 blocks
==5782== suppressed: 0 bytes in 0 blocks
==5782==
==5782== For counts of detected and suppressed errors, rerun with: -v
==5782== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
I just started to learn C++, maybe there is some stupid error that I cannot see.
I know I should also check for example if there was no "out of memory" error when allocating, but I ignore it so that code is more clear. I also know I could use e.g. vector and don't care for the allocation, but I'm still concerned what I do wrong.
C++ provides you with tools, that encapsulate memory management for you.
#include <iostream>
#include <vector>
int main() {
// read the size for the vectors
int n;
std::cin >> n >> '\n';
// allocate vector with n elements
auto input = std::vector<int>{n};
// read the elements
for(int i = 0; i < n; i++) {
std::cin >> std::setw(1) >> input[i];
}
// print them
for(const auto& d : input) {
std::cout << d << std::endl;
}
// allocate the vectors and store 1 in each field.
auto Cl = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}};
auto Cr = std::vector<std::vector<int>>{n, std::vector<int>{n, 1}};
return 0;
// will safely release all the memory here.
}
This looks a lot more like C++, and less like C. The vectors will handle all the memory management automatically for you.
Beware: I have not tested this code, so it will probably contain some bugs. I assume C++11 syntax, but it should be easy to change the code to older C++ syntax as well.
Now that you've added the valgrind output it's clearly the same issue as the one that has an answer here: Valgrind: Memory still reachable with trivial program using <iostream>
The short story is that it's not your code that causes that report. You can remove everything from main() and just return and valgrind will still give you that leak.
Read the accepted answer on that question for the explanation.

Invalid delete[] array of pointer

I am learning to create array of pointer and free up memory. This is my simple code
#include <iostream>
using namespace std;
int main()
{
int* classroom[5];
for (int i = 0; i < 5; i++) {
classroom[i] = new int;
}
for (int i = 0; i < 5; i++) {
classroom[i] = &i;
cout<<*classroom[i]<<endl;
}
for (int i = 0; i < 5; i++) {
delete classroom[i];
}
return 0;
}
When I run in valgrind to check for the memory leak, this is the result
==2868== Memcheck, a memory error detector
==2868== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==2868== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==2868== Command: ./m
==2868==
0
1
2
3
4
==2868== Invalid free() / delete / delete[] / realloc()
==2868== at 0x402ACFC: operator delete(void*) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2868== by 0x8048700: main (in /home/student/Downloads/demo/m)
==2868== Address 0xbea69244 is on thread 1's stack
==2868==
==2868==
==2868== HEAP SUMMARY:
==2868== in use at exit: 20 bytes in 5 blocks
==2868== total heap usage: 5 allocs, 5 frees, 20 bytes allocated
==2868==
==2868== LEAK SUMMARY:
==2868== definitely lost: 20 bytes in 5 blocks
==2868== indirectly lost: 0 bytes in 0 blocks
==2868== possibly lost: 0 bytes in 0 blocks
==2868== still reachable: 0 bytes in 0 blocks
==2868== suppressed: 0 bytes in 0 blocks
==2868== Rerun with --leak-check=full to see details of leaked memory
==2868==
==2868== For counts of detected and suppressed errors, rerun with: -v
==2868== ERROR SUMMARY: 5 errors from 1 contexts (suppressed: 0 from 0)
My question is, why I have received the message "invalid free()/delete/delete[]/realloc[]" ? and how to fix it ?
Thanks,
classroom[i] = &i;
should be:
*classroom[i] = i;
You're replacing the pointer that you allocated with new with the address of the local variable i. Then you later try to delete that pointer, but you can't delete local variables, only variables allocated with new. What you actually want to do is copy the value of i into the dynamically allocated variable.
I think the problem is that by the time you delete each classroom it no longer points to the original memory location of the int created by new because you are not pushing the value of i into the memory location of classroom[i], you are actually changing classroom[i] to point to i's memory location.
Try changing
classroom[i] = &i;
to
*(classroom[i]) = i;
In this loop
for (int i = 0; i < 5; i++) {
classroom[i] = &i;
cout<<*classroom[i]<<endl;
}
You are trashing the memory of the array. You set all of the pointers to the address of i and then when the for loop ends i is destroyed and you now have dangling pointers. attempting to delete them is undefined behavior.

HTML Tidy segfault on TidyBufFree

I'm using Tidy to clean up lots of HTML. The function I'm using is:
std::string cleanHTML (std::string htmlcontent)
{
char* outputstr;
TidyBuffer output ={0};
uint buflen =0;
TidyBuffer errbuf;
int rc = -1;
Bool ok;
TidyDoc tdoc = tidyCreate(); // Initialize "document"
tidyBufInit( &errbuf );
ok = tidyOptSetBool( tdoc, TidyXhtmlOut, yes ); // Convert to XHTML
if ( ok )
rc = tidySetErrorBuffer( tdoc, &errbuf ); // Capture diagnostics
if ( rc >= 0 )
rc = tidyParseString( tdoc, htmlcontent.c_str() ); // Parse the input
if ( rc >= 0 )
rc = tidySaveBuffer (tdoc,&output ); // Tidy it up!
uint yy= output.size;
outputstr = (char*)malloc(yy+10);
uint xx=yy+10;
rc = tidySaveString (tdoc,outputstr,&xx);
std::string cleanedhtml (outputstr);
tidyBufFree(&output);
tidyBufFree(&errbuf);
tidyRelease(tdoc);
return cleanedhtml;
}
The program seems to segfault on tidyBufFree (&output) on a certain call (I don't think there is anything obviously distinctive about the call) having used gdb. There also seems to be a memory leak coming from this function.
Can anyone help?
EDIT:
I've used Valgrind as recommended and the output is below (can someone explain what it means?).
==7860== Process terminating with default action of signal 11 (SIGSEGV)
==7860== Access not within mapped region at address 0x0
==7860== at 0x428B00: tidyBufFree (in /home/sergerold/qt5_episode_analyser/a.out)
==7860== by 0x405EC6: cleanHTML(std::string) (in /home/sergerold/qt5_episode_analyser/a.out)
==7860== by 0x4048A3: get_tvseries(std::string) (in /home/sergerold/qt5_episode_analyser/a.out)
==7860== by 0x403DE2: main (in /home/sergerold/qt5_episode_analyser/a.out)
==7860== If you believe this happened as a result of a stack
==7860== overflow in your program's main thread (unlikely but
==7860== possible), you can try to increase the size of the
==7860== main thread stack using the --main-stacksize= flag.
==7860== The main thread stack size used in this run was 8388608.
==7860==
==7860== HEAP SUMMARY:
==7860== in use at exit: 2,285,594 bytes in 3,638 blocks
==7860== total heap usage: 102,543 allocs, 98,905 frees, 137,801,931 bytes allocated
==7860==
==7860== LEAK SUMMARY:
==7860== definitely lost: 0 bytes in 0 blocks
==7860== indirectly lost: 0 bytes in 0 blocks
==7860== possibly lost: 1,303,686 bytes in 114 blocks
==7860== still reachable: 981,908 bytes in 3,524 blocks
==7860== suppressed: 0 bytes in 0 blocks
==7860== Rerun with --leak-check=full to see details of leaked memory
==7860==
==7860== For counts of detected and suppressed errors, rerun with: -v
==7860== Use --track-origins=yes to see where uninitialised values come from
==7860== ERROR SUMMARY: 113 errors from 17 contexts (suppressed: 0 from 0)
Segmentation fault
SOLVED:
The segmentation fault was caused by tidyBufFree (&output) when &output was empty causing a dereferencing of a null pointer.
Your code seems a lot like this example but with few important differences.
Note in the example the author is not calling tidyBufInit( &errbuf ); this may be your memory leak. To be on the safe side use a tool for memory debugging for instance valgrind. As for the segfault - it seems what you do do free output is correct(at least according to the example) so my guess is that a stack corruption may be causing the problem. Again valgrind may help you find it.
The segmentation fault was caused by tidyBufFree (&output) when &output was empty causing a dereferencing of a null pointer. – user3083672