How to use joern to analysis memory leak? - c

How to query cpg of this code to find the location of un-free memory ?
int bad(void) {
OutsideType my;
my.p = MyAlloc();
my.p = MyAlloc();
MyFree(my.p);
return 0;
}
Try using joern to find the place where the free function is called.

Related

Char* function Never Return value

I'm a newbie of C. Here I write a function to parse http post from browser. Here is my code:
char* HTTP_POST_GET_BODY(char* HttpPost){
char* HttpPostBody = strstr(HttpPost,"\r\n\r\n");
HttpPostBody = HttpPostBody + 4;
if(strcmp(HttpPostBody,"\r\n\r\n") != 0 && strcmp(HttpPostBody,"") != 0){
return HttpPostBody;
}
else{
char* HttpPostBody_IE;
HttpPostBody = strstr(HttpPost,"::");
char* HttpPostBodyEnd = strstr(HttpPost,"HTTP/1.1");
int body_length = HttpPostBodyEnd - HttpPostBody;
strncpy(HttpPostBody_IE,HttpPostBody+2,body_length-2);
return HttpPostBody_IE;
}
}
So basically, if the procedure goes in the "else" it should return a char pointer to caller. I check the debugger. HttpPostBody_IE has a value but when it return it is a null string.
char* http_body = HTTP_POST_GET_BODY(recieve_buffer);
Anyone has an idea about it?
You declare the pointer-variable HttpPostBody_IE but never allocate memory for it.
The call to strncpy(....) should create a core dump.
Try this:
int body_length = HttpPostBodyEnd - HttpPostBody;
HttpPostBody_IE = (char*)malloc(body_length+1);
strncpy(HttpPostBody_IE,HttpPostBody+2,body_length-2);
return HttpPostBody_IE;
Of course, make sure the caller of this functions releases the allocated memory afterwards.
You have a problem in case the function returns from within the if statement. This because no memory is allocated in that case.
You might resolve it this way:
static char HttpPostBody_IE[BIG_ENOUGH_FOR_ANY_SOURCE];
if (....)
{
...
}
else
{
...
strncpy(HttpPostBody_IE, ...);
return (HttpPostBody_IE);
}
Please notice that in this way the variable needs to be static.

Access violation of dynamic array for hashmap

I am having an issue with the table of a little hashmap I am trying to implement.
map.h
typedef struct Map Map;
Map *map_create();
int map_set(Map *map, char *key, void *val);
map.c
const int MAP_INITIAL_SIZE = 100;
typedef struct MapPair MapPair;
struct MapPair
{
char *key;
void *val;
};
struct Map
{
MapPair **table;
int count;
int limit;
};
Map *map_create(void)
{
Map *map = (Map*)malloc(sizeof(Map));
if (!map) return NULL;
map->table = (MapPair**)malloc(MAP_INITIAL_SIZE * sizeof(MapPair));
if (!map->table)
{
free(map);
return NULL;
}
map->count = 0;
map->limit = MAP_INITIAL_SIZE;
return map;
}
void add(MapPair **context, int start, MapPair *pair, int limit)
{
int i = start;
while (context[i] != NULL && strcmp(context[i]->key, pair->key) != 0) // crashing here
{
i++;
if (i == limit) i = 0;
}
context[i] = pair;
}
int map_set(Map *map, char *key, void *val)
{
if (map->count >= map->limit / 2)
{
if (!expand(map)) return 0;
}
MapPair *pair = (MapPair*)malloc(sizeof(MapPair));
if (!pair) return 0;
pair->key = key;
pair->val = val;
add(map->table, hash(key, map->limit), pair, map->limit);
++map->count;
return 1;
}
I was originally developing in pelles c but moved to vs2013 for the debugger when I was experiencing problems. Then in vs2013 the program would crash at the add function but not in pelles c. I am assuming it has something to do with my dynamic array that I plan to be able to expand later.
Can anybody tell me why the program seems to crash when I try to access an index of the dynamic array?
In add function you are checking the table, until you reach the NULL pointer:
while (context[i] != N ...
But when you allocate this table you never set any of those pointers to NULL:
map->table = (MapPair**)malloc(MAP_INITIAL_SIZE * sizeof(MapPair));
You should set them to NULL:
for( size_t i = 0 ; i < MAP_INITIAL_SIZE ; i++ )
map->table[i] = NULL ;
Otherwise you will go out of bounds of that array.
I didn't know Visual could compile pure C projects ! Anyway, your crash is caused by a magic string : http://en.wikipedia.org/wiki/Magic_number_(programming)
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
(SO source : In Visual Studio C++, what are the memory allocation representations?)
Unlike GCC (or pelles I imagine), Visual Studio set uninitialized heap array pointers as 0xCDCDCDCD, not NULL. So your check of context[i] != NULL returns true even though context is not initialized.
... And that's why explicit is always better than implicit.

Setting struct variables - C

I have some code in the following kind of layout, I believe that the topExample/botExample aren't being set properly when I call addTopBotExample. I think this is due to the top bot variables being on the functions stack and so being cleared when the function ends? I have a feeling that perhaps I need to malloc the memory first, but am not sure how I would go about doing this are even if its the right approach.
typedef struct Example Example;
struct Example {
/* normal variables ...*/
Example *topExample;
Example *botExample;
};
....
void addTopBotExample(Example **example, int someVariable) {
Example top = createTopExample(int someVariable); //(createTopExample returns a
//type Example based on some input)
Example bot = createBotExample(int someVariable);
(*example)->topExample = &top;
(*example)->botExample = &bot;
return;
}
If createTopExample isn't allocating memory, this is going to cause problems the moment it's called more than once. Rewrite createTopExample and createBotExample to use malloc and return an Example*. Something like this:
Example* createTopExample(stuff)
{
Example *example = malloc(sizeof(Example));
// ... stuff you do
return example;
}
Then your addTopBotExample would look like this:
void addTopBotExample(Example **example, int someVariable) {
if ((*example)->topExample)
free((*example)->topExample)
if ((*example)->botExample)
free((*example)->botExample)
(*example)->topExample = createTopExample(int someVariable);
(*example)->botExample = createBotExample(int someVariable);
return;
}
Note that this addTopBotExample will free the allocated memory before calling malloc again but before your program ends, you need to call free on any lingering Examples that used this addTopBotExample function:
free(exampleInstanceThatWasPassedIntoAddTopBotExampleAtSomePoint.topExample);
free(exampleInstanceThatWasPassedIntoAddTopBotExampleAtSomePoint.botExample);
You have already everything together. Allocate the Example in createTopExample or createTopExample
Example *createTopExample(int someVariable)
{
Example *x = malloc(sizeof(Example));
/* initialize x */
return x;
}
and in addTopBotExample
void addTopBotExample(Example *example, int someVariable) {
Example *top = createTopExample(int someVariable); //(createTopExample returns a
//type Example based on some input)
Example *bot = createBotExample(int someVariable);
example->topExample = top;
example->botExample = bot;
return;
}
Ooooo, this is bad. The expression "Example top" in the addTopBotExample() function allocated that object on the stack. It'll be trashed after exiting from the function. (Same for "Example bot" on the following line.) Something like this will work better:
void addTopBotExample(Example **example, int someVariable) {
Example *top = createTopExample(someVariable); // NOTE THE *
Example *bot = createBotExample(someVariable); // NOTE THE *
(*example)->topExample = top; // NOT &top !!
(*example)->botExample = bot; // NOT &bot !!
return;
}
And you'll want to write createTopExample and createBotExample so they return pointers:
#include <stdlib.h> // For malloc!
Example *createTopExample(stuff) // Note *. It's returning a pointer.
{
Example *example = malloc(sizeof(Example)); // Allocate on the HEAP. Lives after this function call.
// Fill in the fields of example.
example->field1 = 25; // Note the "->": you're dereferencing a pointer.
example->title = "Example title";
return example;
}

using malloc for the life of the program

gcc 4.4.4 c89
I have always thought of using malloc for the life of the project for being the scope.
But I am just wondering if my idea is the best practice. For example, I initalize an instance of the struct in main. And create 2 functions for creating and destroying. I am just wondering if this is the right thing to do.
I have some skeleton code below.
Many thanks for any advice,
typedef struct Network_dev_t {
size_t id;
char *name;
} Network_dev;
Network_dev* create_network_device(Network_dev *network)
{
network = malloc(sizeof *network);
if(network == NULL) {
return NULL;
}
return network;
}
void do_something(Network_dev *network)
{
/* Do something with the network device */
}
void destroy_network_device(Network_dev *network)
{
free(network);
}
int main(void)
{
Network_dev *network = NULL;
network = create_network_device(network);
/* Do something with the network device */
do_something(network);
destroy_network_device(network);
return 0;
}
Looks good.
I have a point or 2 about create_network_device
Network_dev* create_network_device(Network_dev *network)
no need to pass in a pointer; I'd rather have Network_dev* create_network_device(void)
{
network = malloc(sizeof *network);
the if is not really necessary; if malloc failed the return network at the end of the function is the same as return NULL.
if(network == NULL) {
return NULL;
}
If the allocation succeeded you might want to insure the struct members are in a know state here
/* if (network) { */
/* id = 0; */
/* name = NULL; */
/* } */
return network;
}
This code looks fine to me. I agree with pmg that your create_network_device could use a little work. Just to pull together what he said and make things clearer, here is exactly how I would write the function:
Network_dev *create_network_device()
{
Network_dev *network = malloc(sizeof(*network));
if (network) {
network->id = 0;
network->name = NULL;
}
return network;
}
It is best to allocate memory and free memory in the same function. Just like you open and close files in the same function. You did this by creating and destroying a Network_dev in the main() function, which is good. This makes it easy to confirm that all malloced locations are also freed.
It is best to malloc() something as late as possible and free() it as soon as possible. That is, hold the memory for as short as possible. If your program's job is to do something with Network_dev, you did all right. If your program does a lot of other things, you should do them before malloc() or after free().

Running out of memory.. How?

I'm attempting to write a solver for a particular puzzle. It tries to find a solution by trying every possible move one at a time until it finds a solution. The first version tried to solve it depth-first by continually trying moves until it failed, then backtracking, but this turned out to be too slow. I have rewritten it to be breadth-first using a queue structure, but I'm having problems with memory management.
Here are the relevant parts:
int main(int argc, char *argv[])
{
...
int solved = 0;
do {
solved = solver(queue);
} while (!solved && !pblListIsEmpty(queue));
...
}
int solver(PblList *queue) {
state_t *state = (state_t *) pblListPoll(queue);
if (is_solution(state->pucks)) {
print_solution(state);
return 1;
}
state_t *state_cp;
puck new_location;
for (int p = 0; p < puck_count; p++) {
for (dir i = NORTH; i <= WEST; i++) {
if (!rules(state->pucks, p, i)) continue;
new_location = in_dir(state->pucks, p, i);
if (new_location.x != -1) {
state_cp = (state_t *) malloc(sizeof(state_t));
state_cp->move.from = state->pucks[p];
state_cp->move.direction = i;
state_cp->prev = state;
state_cp->pucks = (puck *) malloc (puck_count * sizeof(puck));
memcpy(state_cp->pucks, state->pucks, puck_count * sizeof(puck)); /*CRASH*/
state_cp->pucks[p] = new_location;
pblListPush(queue, state_cp);
}
}
}
free(state->pucks);
return 0;
}
When I run it I get the error:
ice(90175) malloc: *** mmap(size=2097152) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Bus error
The error happens around iteration 93,000.
From what I can tell, the error message is from malloc failing, and the bus error is from the memcpy after it.
I have a hard time believing that I'm running out of memory, since each game state is only ~400 bytes. Yet that does seem to be what's happening, seeing as the activity monitor reports that it is using 3.99GB before it crashes. I'm using http://www.mission-base.com/peter/source/ for the queue structure (it's a linked list).
Clearly I'm doing something dumb. Any suggestions?
Check the result of malloc. If it's NULL, you might want to print out the length of that queue.
Also, the code snippet you posted didn't include any frees...
You need to free() the memory you've allocated manually after you're done with it; dynamic memory doesn't just "free itself"

Resources