Reputation: 79
I am working on a simple softmodem program. The modem is designed to implement the Audio FSK of a dial-up modem and should be able to initiate a phone call by emitting DTMF tones. Currently I am having some problems with a function which will generate sine values.
double* generate_sine( int numberOfElements, double amplitude,
double phase_in_degrees, double numberOfCycles)
{
static int i;
double *sine_output;
sine_output = malloc( numberOfElements*sizeof(double) );
for( i=0; i<numberOfElements; i++ )
{
sine_output[i] = (amplitude*sin(( (2.0*M_PI*i*numberOfCycles)/(double)numberOfElements )+
((M_PI*phase_in_degrees)/180 )));
}
return sine_output;
}
There is a segmentation error in the function. the variable "i" appears to become a pointer after the first iteration of the loop, its value is 4206692. sine_ptr also has a valid address until the second iteration of the loop at which point it become 0 (NULL). Here is where the function is called. DEFAULT_PHASE = 0.0
int main()
{
int i;
int numElements = 10;
double* sine_ptr = generate_sine( numElements, 0.5, DEFAULT_PHASE, 440 );
for( i=0; i<numElements; i++)
{
printf( "%e \n", *(sine_ptr + i ) );
}
free(sine_ptr);
return 0;
}
After taking all of the edit suggested into consideration I was able to solve the problem in my code, thank you very much for any help that you gave me.
Upvotes: 0
Views: 1204
Reputation: 12099
EDIT Added another point.
Issue Number 1
You are allocating enough memory for 5 elements (numberOfElements is 5). You are then trying to print 10 elements from the initial point. The last 5 elements will be accessing unallocated space and can result in undefined behavior. Including segmentation faults.
Issue Number 2
You are not freeing the pointer to the allocated space but a location 10 places later. This will also cause other problems if you solve the segmentation fault.
Issue Number 3
This is one of the minor ones. But sine_ptr is double
, and trying to show it as int
is undefined. will cause compiler warnings. Even with warnings, the numbers are downcasted. In your case the output will be all zeros. To see correct results, use %lf
.
Use the following code.
int main()
{
int i;
int numElements = 5;
double* sine_ptr = generate_sine( numElements, 0.5, DEFAULT_PHASE, 440 );
for( i=0; i<numElements; i++)
{
printf( "%lf \n", *(sine_ptr + i) );
}
free(sine_ptr);
return 0;
}
Upvotes: 3