Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for memory leak while logging large buffers #27

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 28 additions & 22 deletions src/ctx.c
Original file line number Diff line number Diff line change
Expand Up @@ -249,32 +249,38 @@ void xmpp_log(const xmpp_ctx_t * const ctx,
{
int oldret, ret;
char smbuf[1024];
char *buf;
va_list copy;
char *bigbuf = NULL;
va_list ap_copy;

buf = smbuf;
va_copy(copy, ap);
ret = xmpp_vsnprintf(buf, 1023, fmt, ap);
va_copy(ap_copy, ap);
ret = xmpp_vsnprintf(smbuf, 1023, fmt, ap_copy);
va_end(ap_copy);
if (ret > 1023) {
buf = (char *)xmpp_alloc(ctx, ret + 1);
if (!buf) {
buf = NULL;
xmpp_error(ctx, "log", "Failed allocating memory for log message.");
va_end(copy);
return;
}
oldret = ret;
ret = xmpp_vsnprintf(buf, ret + 1, fmt, copy);
if (ret > oldret) {
xmpp_error(ctx, "log", "Unexpected error");
return;
}
bigbuf = (char *)xmpp_alloc(ctx, ret + 1);
if (!bigbuf) {
bigbuf = NULL;
xmpp_error(ctx, "log", "Failed allocating memory for log message.");
return;
}
oldret = ret;
va_copy(ap_copy, ap);
ret = xmpp_vsnprintf(bigbuf, ret + 1, fmt, ap_copy);
va_end(ap_copy);

if (ret > oldret) {
xmpp_error(ctx, "log", "Unexpected error");
return;
}

if (ctx->log->handler) {
ctx->log->handler(ctx->log->userdata, level, area, bigbuf);
}
xmpp_free(ctx, bigbuf);
} else {
va_end(copy);
if (ctx->log->handler) {
ctx->log->handler(ctx->log->userdata, level, area, smbuf);
}
}

if (ctx->log->handler)
ctx->log->handler(ctx->log->userdata, level, area, buf);
}

/** Write to the log at the ERROR level.
Expand Down