Reputation: 331
I can't understand why the memory leak below happens, and how I can avoid it.
I am using malloc to allocate memory, and I initiate this memory allocated with a loop, copying value by value from string a
to string b
.
As far as my understanding goes, I am not leaving any memory whithout use.
my code:
#include <stdlib.h>
void run_test_one(void)
{
char *a;
char *b;
int i;
a = "up the irons";
b = (char *)malloc(13 * sizeof(char));
i = 0;
while(a[i] != '\0')
{
b[i] = a[i];
++i;
}
b[i] = '\0';
}
int main(void)
{
run_test_one();
return (0);
}
Error:
==9003==ERROR: LeakSanitizer: detected memory leaks
Direct leak of 13 byte(s) in 1 object(s) allocated from:
#0 0x7ffb28c1db40 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb40)
#1 0x55a9533b29c6 in run_test_one test.c:10
#2 0x55a9533b2b04 in main test.c:22
#3 0x7ffb2876fbf6 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21bf6)
SUMMARY: AddressSanitizer: 13 byte(s) leaked in 1 allocation(s).
Upvotes: 1
Views: 3736
Reputation: 331
Memory is allocated by malloc regardless of using it or not. To fix leak you need to free memory.
#include <stdlib.h>
void run_test_one(void)
{
char *a;
char *b;
int i;
a = "up the irons";
b = (char *)malloc(13 * sizeof(char));
i = 0;
while(a[i] != '\0')
{
b[i] = a[i];
++i;
}
b[i] = '\0';
// new code
free(b)
//
}
int main(void)
{
run_test_one();
return (0);
}
Second solution is to use automatic allocation. After your program leaves run_test_one function memory is freed:
#include <stdlib.h>
void run_test_one(void)
{
char *a;
char *b;
int i;
a = "up the irons";
//edit
char b[13];
//
i = 0;
while(a[i] != '\0')
{
b[i] = a[i];
++i;
}
b[i] = '\0';
}
int main(void)
{
run_test_one();
return (0);
}
Upvotes: 1