memory leak in hiredis using valgrind - c

I ran valgrind on my code which uses hiredis, it points out the following individual lines in my code :
redisAsyncConnect()
redisAsyncConnectUnix()
redisLibuvAttach()
uv_loop_new()
I have used 'redisAsyncDisconnect' to free up the memory for the first two cases, couldn't find the right method for third one. For the fourth one i used uv_stop(). But still valgrind says there is definitely a loss in memory in all the four, what is the right way to release the memory ?

Just doing a simple google search shows the method redisLibuvAttach() just does a simple malloc
static int redisLibuvAttach(redisAsyncContext* ac, uv_loop_t* loop) {
redisContext *c = &(ac->c);
if (ac->ev.data != NULL) {
return REDIS_ERR;
}
ac->ev.addRead = redisLibuvAddRead;
ac->ev.delRead = redisLibuvDelRead;
ac->ev.addWrite = redisLibuvAddWrite;
ac->ev.delWrite = redisLibuvDelWrite;
ac->ev.cleanup = redisLibuvCleanup;
redisLibuvEvents* p = (redisLibuvEvents*)malloc(sizeof(*p));
if (!p) {
return REDIS_ERR;
}
m emset(p, 0, sizeof(*p));
if (uv_poll_init(loop, &p->handle, c->fd) != 0) {
return REDIS_ERR;
}
ac->ev.data = p;
p->handle.data = p;
p->context = ac;
return REDIS_OK;
}
The method on_close in that file shows you can simply free(handle->data) :
static void on_close(uv_handle_t* handle) {
redisLibuvEvents* p = (redisLibuvEvents*)handle->data;
free(p);
}
Or just make sure that method is called.

Related

Passing a void (*fn) from a class

I'm writing an auto display turn-off function with ESP32 on Arduino framework with PIO.
I have a Screen class for handling all of the screen functions.
void Screen::turn_off_screen(){
digitalWrite(SCREEN_ENABLE, LOW);
}
void turn_off_screen_wrapper()
{
Serial.println("turn_off_screen_wrapper called");
if (c_screen_Instance != nullptr)
{
c_screen_Instance->turn_off_screen();
}
}
void Screen::auto_display_power_off(int timeout){
Serial.println("auto_display_power_off called");
c_screen_Instance = this;
auto_off_timer = timerBegin(0, 80, true);
Serial.println("auto_off_timer ran");
timerAttachInterrupt(auto_off_timer, &turn_off_screen_wrapper, true);
Serial.println("timerAttachInterrupt ran");
//Converts given seconds from us to seconds
timerAlarmWrite(auto_off_timer,timeout*1000000,false);
timerAlarmEnable(auto_off_timer);
}
The code compiles however I get this when I run it on the board.
auto_display_power_off called
[E][esp32-hal-cpu.c:93] addApbChangeCallback(): duplicate func=400811F8 arg=3FFBDC54
auto_off_timer ran
The screen never gets turned off of course since the callback never runs. Any ideas why this is happening?
is c_screen_Instance global?
is auto_off_timer global?
Consider providing a bit more of your code.
But anyway.
bool addApbChangeCallback(void * arg, apb_change_cb_t cb){
initApbChangeCallback();
apb_change_t * c = (apb_change_t*)malloc(sizeof(apb_change_t));
if(!c){
log_e("Callback Object Malloc Failed");
return false;
}
c->next = NULL;
c->prev = NULL;
c->arg = arg;
c->cb = cb;
xSemaphoreTake(apb_change_lock, portMAX_DELAY);
if(apb_change_callbacks == NULL){
apb_change_callbacks = c;
} else {
apb_change_t * r = apb_change_callbacks;
// look for duplicate callbacks
while( (r != NULL ) && !((r->cb == cb) && ( r->arg == arg))) r = r->next;
if (r) {
log_e("duplicate func=%8p arg=%8p",c->cb,c->arg);
free(c);
xSemaphoreGive(apb_change_lock);
return false;
}
else {
c->next = apb_change_callbacks;
apb_change_callbacks-> prev = c;
apb_change_callbacks = c;
}
}
xSemaphoreGive(apb_change_lock);
return true;
}
This is addApbChangeCallback's declaration.
Your error comes from this line :
while( (r != NULL ) && !((r->cb == cb) && ( r->arg == arg))) r = r->next;
Where r it's a struct to hold all the callbacks.
This error indeed indicates this callback function was already assigned somewhere in your code. r is global, so your code is re-assigning the same callback twice.
Try to either only assign it once, or to unassign the function before assigning it again with removeApbChangeCallback(void * arg, apb_change_cb_t cb) or timerDetachInterrupt
I've also found a reported issue related to timerAttach on the current version here: https://github.com/espressif/arduino-esp32/issues/6730
Try to roll back the Platform PIO's version to a more stable one:
# instead of espressif32
platform = https://github.com/platformio/platform-espressif32.git#<tag-version>
Check on the git link for the available tags you can use.
Problem was that I was attaching the interrupt in the void loop(). Which would run way faster than the actual timer. After moving it to setup (Setup being a placeholder) I plan on having it on a Hardware interrupt it worked as expected.

Freeing memory gives segmentation fault [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I've been trying to work with structures, pointers and memory in C.
I have created this structure
typedef struct {
int id;
char *name;
} Object;
here is constructor
void object_ctor(Object *o, int id, char *name)
{
o->id = id;
o->name = malloc(sizeof(name));
if(sizeof(o->name)!=sizeof(name))
{
o->name=NULL;
}
else
{
strcpy(o->name, name);
}
}
here is decleration of o1
char tmp_name[] = "Hello 1";
Object o1;
object_ctor(&o1, 1, tmp_name);
here is destructor
void object_dtor(Object *o)
{
if(o->name != NULL)
{
free(o->name);
o->name = NULL;
}
}
printing object
void print_object(Object *o)
{
printf("ID: %d, NAME: %s\n", o->id, o->name);
}
calling copy
Object copy;
print_object(object_cpy(&copy, &o1));
and I´m trying create a copy of one structure to another (I have already constructed them).
Object *object_cpy(Object *dst, Object *src)
{
if(src!=NULL)
{
const size_t len_str=strlen(src->name)+1;
dst->name = malloc(10000000);
dst->id = src->id;
strncpy (dst->name, src->name,len_str);
}
if (strcmp(dst->name,src->name)!=0)
{
dst->name = NULL;
}
return dst;
}
But then when I'm trying to free both copy and original src I get a segmentation fault. I've been trying to run it through gdb and it said that I'm freeing same memory twice so I assume that the code for copying is wrong, but I don't know where.
And here is code that gives me segmentation fault
printf("\nCOPY EMPTY\n");
object_dtor(&copy);
o1.id = -1;
free(o1.name);
o1.name = NULL;
object_cpy(&copy, &o1);
print_object(&copy);
print_object(&o1);
I´m including these libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
I'm using the std=c99 flag for to compile.
There is at least a problem here:
void object_ctor(Object *o, int id, char *name)
{
o->id = id;
o->name = malloc(sizeof(name));
if (sizeof(o->name) != sizeof(name))
{
o->name = NULL;
}
else
{
strcpy(o->name, name);
}
}
sizeof(name) is not the length of the string pointed by name. You need strlen(name) + 1 (+1 for the NUL terminator).
And your test if (sizeof(o->name) != sizeof(name)) is pointless, and I'm not sure what you're trying to achieve here.
You probably want this:
void object_ctor(Object *o, int id, char *name)
{
o->id = id;
o->name = malloc(strlen(name) + 1);
if (o->name != NULL)
strcpy(o->name, name);
}
There are similar problems in object_cpy:
pointless use of strncpy
pointless allocation of a 10Mb buffer
pointless test strcmp(dst->name, src->name)
You probably want this:
Object *object_cpy(Object *dst, Object *src)
{
if (src != NULL)
{
const size_t len_str = strlen(src->name) + 1;
dst->name = malloc(len_str);
if (dst->name != NULL)
{
dst->id = src->id;
strcpy(dst->name, src->name);
}
}
return dst;
}
With these corrections following code works fine:
int main()
{
char tmp_name[] = "Hello 1";
Object o1, copy;
object_ctor(&o1, 1, tmp_name);
object_cpy(&copy, &o1);
print_object(&copy);
print_object(&o1);
object_dtor(&o1);
object_dtor(&copy);
}
Event if this is not directly an answer to your problem, I'll give you how I organize my code in order to avoid memory problem like yours.
First, it all resolve around a structure.
To each structure, if needed, I do a "Constructor" and a "Destructor".
The purpose of the constructor is simply to set the structure in a coherent state. It can't never fail (implying that any code that could fail, like malloc, should not be in the constructor).
The purpose of the destructor is to clean the structure.
One little trick that I like to use is to put the constructor in a macro, allowing me to do something like 'Object var = OBJET_CONSTRUCTOR'.
Of course, it's not alway possible, it's up to you to be carreful.
For your code, it could be :
typedef struct {
int id;
char *name;
} Object;
#define OBJECT_CONSTRUCTOR {.id = -1,\ \\ Assuming -1 is relevant in your case, like an error code or a bad id value. Otherwise, it's useless.
.name = NULL}
void Object_Constructor(Object *self)
{
Object clean = OBJECT_CONSTRUCTOR;
*self = clean;
}
void Object_Destructor(Object *self)
{
free(self->name);
}
Here we go.
How to use it is simple : You always begin by the constructor, and you alway end by the destructor. That's why it's useless to set the char pointer "name" to NULL in the destructor, because it should not be used after by any other function that the constructor.
Now, you can have "initialisation" function. You can do a plain initialisation (it is your constructor function), or a copy initialisation, etc etc
Just keep in mind that the structure have been called into the constructor. If not, it's the developer fault and you do not have to take that in count.
A behavior that can be nice is, in case of error, to not modify the structure.
Either the structure is entierly modified in succes, or not at all.
For complex structure that can fail at many point, you can do that by "swapping" the result at the end.
void Object_Swap(Object *first, Object *second)
{
Object tmp = OBJECT_CONSTRUCTOR;
tmp = *fisrt;
*first = *second;
*second = tmp;
}
bool Object_InitByPlainList(Object *self, int id, consr char *name)
{
Object newly = OBJECT_CONSTRUCTOR;
bool returnFunction = false;
newly.id = id;
if (!(newly.name = strdup(name))) {
printf("error : %s : strdup(name) : name='%s', errno='%s'.\n", __func__, name, strerror(errno));
goto END_FUNCTION;
}
// Success !
Object_Swap(self, &newly);
returnFunction = true;
/* GOTO */END_FUNCTION:
Object_Destructor(&newly);
return (returnFunction);
}
It may be seem overcomplicated at the first glance, but that organization allow you to add more futur step "that can fail" cleanly.
Now, you can even do something this simply :
bool Object_InitByCopy(Object *dst, Object *src)
{
return (Object_InitByPlainList(dst, src->id, src->name));
}
All you have to do is to say in the documentation :
The first function to be called have to be "Object_Constructor"
After the "Object_Constructor", only the "Object_Init*" function can be called.
The last function to be call have to be "Object_Destructor"
That's all. You can add any "Object_*" function that you whant, like :
void Object_Print(const Object *self)
{
printf("ID: %d, NAME: %s\n", self->id, self->name);
}
Hope this organization will solve your memory problem.
An example :
int main(void)
{
Object test = OBJECT_CONSTRUCTOR;
Object copy = OBJECT_CONSTRUCTOR;
if (!Object_InitByPlainList(&test, 1, "Hello World !")) {
// The function itself has logged why it has fail, so no need to add error printf here
return (1);
}
Object_Print(&test);
if (!Object_Copy(&copy, &test)) {
return (1);
}
Object_Destructor(&test);
Object_Destructor(&copy);
return (0);
}

Apparently allocating memory and freeing it properly but program still crashes

So I've got a weird problem and can't seem to solve it. I have an ADT called TEAM:
typedef struct Team {
char *name;
int points;
int matches_won;
int goal_difference;
int goals_for;
}TEAM;
I created a function to initialize variables of the TEAM* type with a given name:
TEAM *createTEAM (char *name){
int error_code;
if (name != NULL){
if(strcmp(name, "") != 0){
TEAM *new_team = (TEAM*)malloc(sizeof(TEAM));
new_team->name = (char*)malloc(sizeof(char)*strlen(name));
strcpy(new_team->name, name);
new_team->points = 0;
new_team->matches_won = 0;
new_team->goal_difference = 0;
new_team->goals_for = 0;
return new_team;
}else{
error_code = EMPTY_STRING_CODE;
}
} else {
error_code = NULL_STRING_CODE;
}
printf("Erro ao criar time.\n");
printError(error_code);
return NULL;
}
I also created a function to delete one of these TEAM* variables properly:
void deleteTEAM (TEAM *team_to_remove){
free(team_to_remove->name);
team_to_remove->name = NULL;
free(team_to_remove);
team_to_remove = NULL;
}
But when one or multiple test functions that I created (example below) run, the program sometimes crashes, sometimes doesn't. I've noticed that changing the names I use affects whether it crashes or not, even if they don't affect the test results.
int create_team_01(){
int test_result;
TEAM *Teste = createTEAM("Cruzeiro");
if (strcmp(Teste->name, "Cruzeiro") == 0){
test_result = TRUE;
}else test_result = FALSE;
_assert(test_result); //just a macro function that will check the argument and return 1 if it's false
deleteTEAM(Teste);
return 0;
}
I don't see any problems with memory allocation or freeing. Still, the debugger complains a lot about the first free() (can't find bounds) of the deleteTEAM function. Any ideas? Thanks a lot in advance for any help.
P.S.: I've even tried checking the mallocs' results, but it doesn't seem to be the problem either, so I removed it for the sake of simplicity.

UTHash in function call does iteration once but not second time

I am having some issues with usage of a uthash on a local variable.
My code looks something like this, query_dict is a local variable uthash:
main functions:
query* query_dict = NULL;
split_query_into_terms(querystr, &query_dict);
print_query_struct(&query_dict);
prefetch_tokens(&query_dict);
more closely:
void prefetch_tokens(query** query_dict) {
query* entry;
for(entry=*query_dict; entry != NULL; entry=entry->hh.next) {
handle_token(entry->term);
}
}
void add_term_to_query(query** query_dict, char* term, dictionary_entry* dict_entry) {
// if query in hashtable, increase score:
query* myq = NULL;
if(*query_dict != NULL)
HASH_FIND_STR(*query_dict, term, myq);
if(myq == NULL) {
myq = init_alloc_query(term);
myq->dict_entry = dict_entry;
HASH_ADD_KEYPTR(hh, *query_dict, myq->term, strlen(myq->term), myq);
} else {
myq->score += 1.0f;
}
}
void split_query_into_terms(char* querystr, query** query_dict) {
char* myquery = strdup(querystr);
char* reentrant_saver;
char* token;
token = strtok_r(myquery, " \n", &reentrant_saver);
while(token != NULL) {
dictionary_entry* dict_entry = find_dict_entry(token);
if(dict_entry) {
add_term_to_query(query_dict, token, dict_entry);
}
token = strtok_r(NULL, " \n", &reentrant_saver);
}
}
void print_query_struct(query** query_dict) {
query* entry;
for(entry=*query_dict; entry != NULL; entry=entry->hh.next) {
fprintf(stdout, "%s: %f\n", entry->term, entry->score);
}
}
The call to print_query_struct runs fine, but the call to prefetch tokens, does one iteration, then crashes with:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000001000000000
0x0000000100004959 in prefetch_tokens (query_dict=0x7fff5fbffa30) at search/c_port/search.c:241
241 handle_token(entry->term);
(gdb) bt
0 0x0000000100004959 in prefetch_tokens (query_dict=0x7fff5fbffa30) at search/search.c:241
1 0x00000001000049d2 in search (querystr=0x7fff5fbffbe5 "wash") at search/search.c:255
2 0x0000000100004a20 in main (argc=2, argv=0x7fff5fbffa80) at search/search.c:263
the address, 0x0000001000000000 always being the same.
I have been trying all kinds of different things, but could not get it working.
Does anyone here know what's going on?
structs:
typedef struct {
char* word;
uint32_t byte_offset;
uint32_t occurences;
uint32_t occurences_abstract;
postings_entry* posting;
UT_hash_handle hh; /* makes this structure hashable */
} dictionary_entry;
/* query has a number of terms (strings) */
typedef struct {
char* term;
float score;
dictionary_entry* dict_entry;
UT_hash_handle hh;
} query;
Edit:
I have simplified the code quite a bit and made a smaller runnable example, but in essence, this is the code that fails: http://pastebin.com/qdDiQMG0
compile, then run with ./binary
eg. ./binary "wash help"
Edit 2:
Solved it even though I do not quite understand why it worked:
rewrote the init_alloc_query from:
query* init_alloc_query() {
query* query = malloc(sizeof(query));
query->term = NULL;
return query;
}
to work like this:
void init_alloc_query(query** q) {
*q = malloc(sizeof(query));
(*q)->term = NULL;
}
And everything runs fine.
Solved it even though I do not quite understand why it worked: rewrote the init_alloc_query from:
query* init_alloc_query() {
query* query = malloc(sizeof(query));
query->term = NULL;
return query;
}
to work like this:
void init_alloc_query(query** q) {
*q = malloc(sizeof(query));
(*q)->term = NULL;
}
And everything runs fine.

Hooking IAT address is incorrect

I'm trying to locate the entry for wglGetProcAddress (OpenGl32.dll) imported in a test application. For some reason, the import whose name is "wglGetProcAddress" does point to the same function returned by calling GetModuleHandle and GetProcAddress on Opengl32.dll.
The executable file has been loaded into memory and is a process with its thread currently suspended. The following code correctly reads the names modules and their functions imported by that executable. Hence, the IAT should not contain RVAs since it has been loaded.
HMODULE h = GetModuleHandle("OPENGL32.dll");
DWORD expect_addr = (DWORD)GetProcAddress(h, "wglGetProcAddress");
PIMAGE_IMPORT_DESCRIPTOR import_desc = (PIMAGE_IMPORT_DESCRIPTOR)(pmem + import_dir);
while (import_desc->Name)
{
PIMAGE_THUNK_DATA thunk = (PIMAGE_THUNK_DATA)(pmem + import_desc->OriginalFirstThunk);
while (thunk->u1.Function)
{
PIMAGE_IMPORT_BY_NAME import = (PIMAGE_IMPORT_BY_NAME)(pmem + thunk->u1.AddressOfData);
printf("%s 0x%X\n", import->Name, thunk->u1.Function);
if ((DWORD)expect_addr == (DWORD)thunk->u1.Function)
{
printf("Found wglGetProcAddress\n");
}
else if (!strcmp((const char*)import->Name, "wglGetProcAddress"))
{
printf("Found wglGetProcAddress's import, but the function has a different value.\n");
}
++thunk;
}
++import_desc;
}
GetProcAddress from that original value returns the address 60XXC245 where XX varies, but thunk->u1.Function always returns 0xA46D8. Everything in thunk->u1 (Function, AddressOfData, Ordinal and ForwarderString) has
the same value. The names of the import descriptors and imports correct. Does anyone see what I'm missing?
Edit:
I'm trying something else: I'm scanning pmem (image of the executable in memory) for what I expect is the IAT entry, but it doesn't locate that either:
HMODULE h = GetModuleHandle("OPENGL32.dll");
DWORD expect_addr = (DWORD)GetProcAddress(h, "wglGetProcAddress");
printf("Looking for 0x%X\n", expect_addr);
for (int i = 0; i < pmem_size - sizeof(DWORD); i++)
{
if (*(DWORD*)(pmem + i) == expect_addr)
{
printf("0x%X at 0x%X\n", *(DWORD*)(pmem + i), i);
}
}
SOLVED: I didn't realize it, but calling CreateProcess with CREATE_SUSPENDED prevents the windows loader from populating FirstThunk with the actual addresses. If I let the process run for a second and then suspend the thread, it hooks the IAT address perfectly fine. Now I have to go look for a way to fix that.
u1.Function represents the relative offset to the IMAGE_IMPORT_BY_NAME entry (or the ordinal entry if the IMAGE_ORDINAL_FLAG bit is set). this is why it doesn't match the value from GetProcAddress, because it isn't the address of the function, its the address of the function import entry.
When you have found the thunk matching your function, you need to use this too lookup the virtualized address altered by the linker, form the other thunk list. altering your code so it does this yeilds:
while (import_desc->Name)
{
PIMAGE_THUNK_DATA thunk = (PIMAGE_THUNK_DATA)((DWORD)GetModuleHandle(NULL) + import_desc->OriginalFirstThunk);
int i = 0;
while (thunk->u1.Function)
{
PIMAGE_IMPORT_BY_NAME import = (PIMAGE_IMPORT_BY_NAME)((DWORD)GetModuleHandle(NULL) + thunk->u1.AddressOfData);
void** p = (void**)((DWORD)GetModuleHandle(NULL) + import_desc->FirstThunk);
printf("%s 0x%X\n", import->Name, p[i]);//thunk->u1.Function);
if ((DWORD)expect_addr == (DWORD)p[i])
{
printf("Found wglGetProcAddress\n");
}
else if (!strcmp((const char*)import->Name, "wglGetProcAddress"))
{
printf("Found wglGetProcAddress's import, but the function has a different value.\n");
}
++thunk;
}
++import_desc;
}
To get the IAT entries, I do things a little differently:
inline const void** GetImportAddress(HMODULE hModule, IMAGE_IMPORT_DESCRIPTOR* pTable, size_t nThunk)
{
const void** pAddressBlock = (const void**)((DWORD)hModule + pTable->FirstThunk);
return &pAddressBlock[nThunk];
}
const void** GetImport(HMODULE hModule, const char* szDll, const char* szFunction)
{
const char* szDllName = NULL;
IMAGE_IMPORT_DESCRIPTOR* pTable = GetImportDescriptor(hModule);
while(pTable->Characteristics != 0 && (szDllName = GetImportTableName(hModule,pTable)) != NULL)
{
if(!lstrcmpiA(szDll,szDllName))
{
IMAGE_THUNK_DATA* pThunkData = GetThunk(hModule,pTable);
if(pThunkData != NULL)
{
size_t nThunk = 0;
while(pThunkData->u1.AddressOfData != 0)
{
if(pThunkData->u1.Ordinal & IMAGE_ORDINAL_FLAG)
{
if(IMAGE_ORDINAL32(pThunkData->u1.Ordinal) == (DWORD)szFunction)
return GetImportAddress(hModule,pTable,nThunk);
}
else
{
IMAGE_IMPORT_BY_NAME* pImport = GetImport(hModule,pThunkData);
if(!lstrcmpA(szFunction,(const char*)pImport->Name))
return GetImportAddress(hModule,pTable,nThunk);
}
nThunk++;
pThunkData++;
}
}
}
pTable++;
}
return NULL;
}

Resources