Below is my C program:
When I run "leaks -atExit -- ./test" there are no memory leaks.
But when I run "./test" i get the below error.
malloc: *** error for object 0x7f95324059c8: pointer being freed was not allocated
Where am I going wrong here in my memory allocation?
CodePudding user response:
**args
is not the number of arguments that were passed to free_args
. You're using a NULL
sentinel to indicate the end of the arguments, so you should check for that.
Also, the types of the arguments are char**
, not char*
.
When looping over the arguments, you need to start with args
, then use va_arg
to get the additional arguments.
void free_args(char **args, ...){
va_list arg;
va_start(arg, args);
for (char **ar = args; ar != NULL; ar = va_arg(arg, char**)) {
free(ar);
}
va_end(arg);
}
Note that this does have a memory leak. You're freeing the upArgs
and lowArgs
arrays, but not freeing all the strings that they point to. I'm not showing how to fix that, I assume it was intention so that leak
would report the problem.
When I use
leaks --atExit -- ./testleaks a Bcd EF
I get the following leak report:
Process 30435: 8 leaks for 128 total leaked bytes.
8 (128 bytes) << TOTAL >>
1 (16 bytes) ROOT LEAK: 0x13f606880 [16]
1 (16 bytes) ROOT LEAK: 0x13f606890 [16]
1 (16 bytes) ROOT LEAK: 0x13f6068a0 [16]
1 (16 bytes) ROOT LEAK: 0x13f6068b0 [16]
1 (16 bytes) ROOT LEAK: 0x13f6068f0 [16]
1 (16 bytes) ROOT LEAK: 0x13f606900 [16]
1 (16 bytes) ROOT LEAK: 0x13f606910 [16]
1 (16 bytes) ROOT LEAK: 0x13f606920 [16]