⚠️ This tool modifies your original files. It saves copies of your files in a hidden directory. When your done using this tool, you can use the --reverse option to get your original file back. Because this tool is still being tested, make sure you make a backup of your files.
The malloc_failer let's you fail a specific malloc after X times. This can be used to check whether you have memory leaks when you exit your program because a malloc failed.
It adds the following wrapper code to your code (the X is given when running this script, explained in the Usage section):
#include <stdlib.h>
static void *xmalloc(size_t size)
{
static int fail = X;
static int i = 1;
if (i == fail)
return (NULL);
i++;
return (malloc(size));
}
It then sandwiches your malloc between this #define directive:
#define malloc(x) xmalloc(x)
int **matrix = (int **)malloc(size); /* This would be the malloc you want to fail */
#undef malloc
Clone this repository. The only file you need is malloc_failer.sh, which is an executable.
You can add this tool to a location in your PATH so that you can use it for every project.
There are 3 things you need to specify:
- The file from which to fail a malloc.
- The line number of the malloc.
- X, which is a number at which to fail the malloc.
The format is:
./malloc_failer.sh [file_to_be_tested.c] [line_number_of_malloc] [at_which_malloc_to_fail]
Below you can see an example program. Let's say this file is called matrix.c.
#include <stdlib.h>
int main(void)
{
int i = 0;
int j = 0;
int rows = 4;
int columns = 4;
int **matrix;
matrix = (int **)malloc(sizeof(int *) * rows);
if (matrix == NULL)
return (-1);
while (i < rows)
{
matrix[i] = (int *)malloc(sizeof(int) * columns); /* ----- line 16 ----- */
if (matrix[i] == NULL)
return (-1);
while (j < columns)
{
matrix[i][j] = 0;
j++;
}
j = 0;
i++;
}
/* Free all data */
i = 0;
while (i < rows)
{
free(matrix[i]);
i++;
}
free(matrix);
return (0);
}
This program contains leaks when an allocation of matrix[i]
fails (line 16). To fail the malloc on line 16 at the third time, you can run:
./malloc_failer.sh matrix.c 16 3
Your original file is modified. A copy of your file is saved in the .malloc_failer/ directory with the .orig prefix. Now you can run your program as always with a memory error detection tool, like:
gcc -Wall -Wextra -Werror -fsanitize=address -g matrix.c
To get your original file back, you can run:
./malloc_failer.sh --reverse
The reverse option makes sure your project directory is the same as before you ran the malloc_failer.
- Add calloc and realloc.
- Make more user friendly.
Found a bug? Ran into a specific problem? Missing a feature? Feel free to file a new issue with a respective title and description on the issue page. You can also ask questions in GitHub Discussion.
Thanks Tishj for finding some bugs and coming up with ideas for the malloc_failer!