Reputation: 4585
Is there a leak in this C code?
Although the answer is coming correct, but just wanted to know if it is Ok to write like this:
// _mm_adds_epi16 : Adds the 8 signed 16-bit integers in a to the 8 signed
//16-bit integers in b and saturates
__m128i t7=_mm_adds_epi16( t5 ,t6 );
unsigned short *p= (unsigned short *)malloc(8);
p=(unsigned short *)&t7;
for(int i=0;i<8;i++)
{
printf("%d\n", p[i]);
}
Updated
So now I am updating it as follows:
// _mm_adds_epi16 : Adds the 8 signed 16-bit integers in a to the 8 signed
//16-bit integers in b and saturates
__m128i t7=_mm_adds_epi16( t5 ,t6 );
unsigned short *p= (unsigned short *)malloc(8);
p=(unsigned short *)&t7;
for(int i=0;i<8;i++)
{
printf("%d\n", p[i]);
}
free(p);
Do I still have leak?
What is the correct way to print t7
Upvotes: 1
Views: 159
Reputation: 24447
Every malloc
in C needs to have some corresponding free
which is reachable before termination. Any exception to this constitutes a memory leak.
You store the return of malloc
in p
and lose the pointer by overwriting it. As such there is no chance for the pointer to be freed. In your particular case, the malloc
itself is redundant since you are not using the return in any way.
In response to your question of whether the new code has a memory leak, yes it does. malloc
allocates memory and returns a pointer to the allocated memory. You are losing the pointer by overwriting its value then never using the allocated memory. Even worse you are now calling free
on what appears to be an automatic variable which is undefined behaviour.
If the printing is working correctly, you can just do this:
__m128i t7 = _mm_adds_epi16(t5, t6);
unsigned short *p = (unsigned short *)&t7;
for(int i=0;i<8;i++) {
printf("%d\n", p[i]);
}
The malloc
is redundant because you are not even using the memory it allocates.
Upvotes: 5
Reputation: 20314
free
will release any memory allocated by malloc
.
unsigned short *p= (unsigned short *)malloc(8);
Here you have allocated 8 bytes of memory and have assigned that memory address to p
.
p=(unsigned short *)&t7;
You just assigned a different memory address to p
; the previous memory address (the one returned bymalloc
) has been overwritten. We no longer know the memory address where our 8 bytes have been allocated.
free(p);
Memory leak. It's not pointing to the memory allocated by malloc
anymore.
Upvotes: 0
Reputation: 272467
Yes, there is a leak. You immediately overwrite the pointer that's storing the address of the dynamically-allocated memory. So that memory is no longer reachable.
Upvotes: 8