Help needed in max sum subarray for Circular Array : How to return array from a function

Help needed in max sum subarray for Circular Array written by me

Link to the code:
https://ide.codingblocks.com/s/72975

It gives runtime error-SIGSEGV
“A SIGSEGV is an error(signal) caused by an invalid memory reference or a segmentation fault. You are probably trying to access an array element out of bounds or trying to use too much memory.”
PS:
If we return the address of the local variable, then the variable must be deallocated , when the function ends.
Hence the pointer in the main may be getting some garbage values. Can someone help here? :tired_face:
How to do it?

Hi Sachin,

Yes, the local variables are destroyed after the function gets fully executed, so, you can’t access them outside the function or also can’t return their address. So, to overcome this issue you can do one thing declare
int* result; in main()
and pass it as an argument in kadane function like this
int* kadane(int arr[],int* result, int length, bool maximum)
then you can return result; in kadane()
and get its value in main() like this
int* candidate1=kadane(arr,result, length, true);

I followed the instructions above said, still runtime error.
I think we could allocate some memory to result in main using new (or define it as array of 3), as it currently points to some garbage location. and also some memory to candidate1 and candidate2… as they both point to same address stored by result and result changes in every call to function.

Please help.

Hi Sachin,

Earlier, I have told you the modifications which you should make for rectifying SIGSEGV error.
Now, I just checked your code, in your code Kadane() is not correct, there is no point to take maximum and !maximum,
you can write the simple kadane() and make 2 calls one for kadane(normal_array) and another for kadane(negative_array). kadane(negative_array) will basically give the sum which will not contribute to the max sum of the circular array, so we can find out the sum of non-contributing elements and subtract this sum from the total sum. Then, just check which sum is greater kadane(normal_array) or totalsum(normal_array)-kadane(negative_array) and the greater value will be the result.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.