I have read through a lot of posts giving ways in which you can return an array of type int from a function. I have attempted to follow the approach of dynamically allocating the memory inside of the function using the malloc()
function.
In the example code, I am using a function foo
which calculates peaks in an array which are greater than a specified value.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* function declaration */
int *foo(int arr[],int size);
int main()
{
int test[] = {1,2,1,4,5,2,7,8,9,1}; //array of test data.
int *p;
p = foo(test,10);
int w;
for(w=0;w<5;w++)
{
printf(" Peak %d\t",p[w]); // This line is giving a non sensible answer.
}
free(p); // free the memory
return 0;
}
int *foo(int arr[],int size) {
int j;
int Peak_min = 3; // Minimum peak height
int *ret = malloc(size * sizeof(*ret));
if(!ret) return 1;
for (j = 0; j < size -1; ++j)
{
if ( (arr[j] < arr[j+1]) && (arr[j+1] > arr[j+2]) && (arr[j+1] > Peak_min))// Peak criteria
{
ret[j] = arr[j+1];
printf(" Peak_No %d",ret[j]); // This line is giving the correct output.
}
}
return ret;
}
The output printed in the function gives 5 and 9, as expected. However, the output when I call the function in int main()
gives non-sensible values. I am struggling to find the error with my code, any suggestions on how I can debug/fix this?
Update
I edited the for loop in the fucntion foo to
for (j = 0; j < size -2; ++j)
{
if ( (arr[j] < arr[j+1]) && (arr[j+1] > arr[j+2]) && (arr[j+1] > Peak_min))// Peak criteria
{
ret[j] = arr[j+1];
printf(" Peak_No %d",ret[j]); // This line is giving the correct output.
}
else
{
ret[j] = 0;
}
}
I am now getting the output I wanted.
malloc()
returns unitialized memory.
Inside the function, the assignment of ret[j]
is conditional. You never know for sure that which or any index element is actually initialized. After returning the pointer, you unconditionally index into the pointer any to read the values which may be very well unitialized.
In case, you are returning the pointer with the same assignment condition, you can at least use calloc()
which returns 0-filled memory, so at least, you have a deterministic value. However, this will fail to differentiate between a left-over index element and an element actually having a value of 0. For better precision, you can memset()
the malloc()
-ed memory to some guard value which indicates that those node values are not assigned.
Also, another quickfix would be, add one else
condition which basically helps to unconditionally assign a value to each element.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments