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
Every
mallocin C needs to have some correspondingfreewhich is reachable before termination. Any exception to this constitutes a memory leak.You store the return of
mallocinpand lose the pointer by overwriting it. As such there is no chance for the pointer to be freed. In your particular case, themallocitself 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.
mallocallocates 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 callingfreeon what appears to be an automatic variable which is undefined behaviour.If the printing is working correctly, you can just do this:
The
mallocis redundant because you are not even using the memory it allocates.