When I said: "Returned variable is NULL.", I meant that it returns a stuct that contains two pointers and they == NULL.
struct LandR_8
{
unsigned char *L; // For L channel.
unsigned char *R; // For R channel.
}; // These pointers point to the allocated memory.
struct LandR_8 LRChannels_8;
My function:
struct LandR_8 sepChannels_8( unsigned char *smp, unsigned char *L, unsigned char *R, unsigned long N, struct LandR_8 LRChannels )
{
int i;
L = malloc(N / 2);
R = malloc(N / 2);
for ( i = 0; i < (N / 2) ; i++ ) // separating
{
L[i] = smp[2 * i + 0];
R[i] = smp[2 * i + 1];
}
// L and R don't need `free()`.
return LRChannels;
}
returns variable LRChannels of type struct LandR:
I call my function like so:
LRC_8 = sepChannels_8( ptrSamples_8, ptrSamples_8_L, ptrSamples_8_R, n, LRChannels_8 );
The problem is that after using that function LRC_8.L == NULL.
Why does it so?
Your function interface is inconsistent.
You don't need to have L and R as parameters as you create them from inside.
Having a LRChannels coming in is contraproductive as well.
The easiest design would probably be
struct LandR_8 sepChannels_8( unsigned char *smp, unsigned long N)
{
unsigned char *L;
unsigned char *R;
struct LandR_8 LRChannels;
int i;
L = malloc(N / 2);
R = malloc(N / 2);
for ( i = 0; i < (N / 2) ; i++ ) // separating
{
L[i] = smp[2 * i + 0];
R[i] = smp[2 * i + 1];
}
// L and R don't need `free()`.
LRChannels.L = L;
LRChannels.R = R;
return LRChannels;
}
You return the LRChannels parameter, but you never modify it, so if LRChannels.L was NULL when the function was called, you will have LRC_8.L == NULL after the assignment.
There is more wrong with the function:
struct LandR_8 sepChannels_8( unsigned char *smp, unsigned char *L, unsigned char *R,
unsigned long N, struct LandR_8 LRChannels )
{
int i;
L = malloc(N / 2);
R = malloc(N / 2);
C is a pass-by-value language, so the two pointers L and R in the function are copies of the arguments passed. Any changes you make to these parameters are not visible outside the function. You malloc memory for them
for ( i = 0; i < (N / 2) ; i++ ) // separating
{
L[i] = smp[2 * i + 0];
R[i] = smp[2 * i + 1];
}
and fill it, but never use that in any other way. When the function returns, the allocated memory is no longer reachable, it is leaked. Since neither the pointers in the caller are changed nor the memory they point to, these two should not be arguments to the function at all - or, if you want to modify the pointers in the caller, you need to pass their addresses.
// L and R don't need `free()`.
return LRChannels;
}
LRChannels is the unmodified copy of the argument.
You probably intended something like setting the L and R members of LRChannels to L and R before returning,
LRChannels.L = L;
LRChannels.R = R;
return LRChannels;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With