Why Does Using an Uninitialized Pointer Cause a Segmentation Fault in Recursion?

  • Context: Comp Sci 
  • Thread starter Thread starter anonim
  • Start date Start date
  • Tags Tags
    Function Recursion
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
4 replies · 2K views
anonim
Messages
39
Reaction score
2
Homework Statement
Calculate the Math Formula
Relevant Equations
-
C:
double foo(int arr[], double *ave, int index){
  double *s;
  *s=*ave;
    // calculation//
    return(foo (arr,ave,index));
// other calculation//
}

I want to keep the ave value during the recursion, because after ave is calculated, I will do another calculation is recursively in this function. But I write like this, I am getting segmentation fault.
 
on Phys.org
anorlunda said:
Hint: How many levels deep will the recursive calls go in your code?
I did not understand what you say. the function will call itself about 560 times
 
anorlunda said:
Hint: How many levels deep will the recursive calls go in your code?
anonim said:
I did not understand what you say. the function will call itself about 560 times
Based on what you posted, the function will run until there is no more stack memory for it.
anonym said:
C:
double foo(int arr[], double *ave, int index){
  double *s;
  *s=*ave;
    // calculation//
    return(foo (arr,ave,index));
// other calculation//
}

I want to keep the ave value during the recursion, because after ave is calculated, I will do another calculation is recursively in this function. But I write like this, I am getting segmentation fault.
Right, and @anorlunda's hint might have something to do with why you're getting this fault.
Are there any conditions in which the function returns without calling itself? You don't show any in this code snippet. In particular, how does the part you have commented as "other calculation" actually get executed?
 
anonim said:
Homework Statement:: Calculate the Math Formula
Relevant Equations:: -

C:
double foo(int arr[], double *ave, int index){
  double *s;
  *s=*ave;
    // calculation//
    return(foo (arr,ave,index));
// other calculation//
}

I want to keep the ave value during the recursion, because after ave is calculated, I will do another calculation is recursively in this function. But I write like this, I am getting segmentation fault.

You're assigning to the address of an uninitialised pointer:
C:
  double *s;
  *s=*ave;
Why is s a pointer here?