0

i'm writing a function that gets passed an array of length 100, full of random integers between 0 and 25 (to be specific the data type is double, but the numbers themselves are whole numbers), that has already been sorted into increasing order. What it's supposed to do is find and return the mode (as well as print a simple histogram as a visual aid), and it works sometimes, but other times results in a *** stack smashing detected *** error. (also i am using replit as my IDE) this is what the function looks like:

double mode(double * n){int x=0,r=0,R=0;
for(int i=1;i!=100;i++){
  if(n[i]==n[i-1])r++;
  else {
    if(r>R){
      R=r;
      x=n[i-1];}
    cout<<n[i-1]<<" ";
    for(int L=0;L!=r;L++)cout<<"*";
    r=0;
    cout<<endl;}}
return x;}

i've tried running the program in the debugger but haven't gotten the error while doing so. also i've noticed that whenever the error happens, for some reason a random very large/small number (in scientific notation) gets printed in between random lines of the output, and i can't figure out where this is coming from. example:

0 **
5.22851e-33 <--this guy here is what im talking about
1 
2 *
3 ******
4 *
5 *****
6 ***
7 *****
8 *****
9 **
10 ***
11 ***
12 *****
13 *****
14 **
15 **
16 ***
17 ***
18 *
19 ****
20 **
21 ***
22 **
23 ****
24 
*** stack smashing detected ***: terminated
signal: aborted (core dumped)
  • Most likely you are going out of bounds of your `n` array. – drescherjm Mar 22 '23 at 18:57
  • 3
    You **urgently** need to learn to write [properly indented code](https://en.wikipedia.org/wiki/Indentation_style). Whatever you're doing wrong is made 10x harder to spot in this hairball of clutter. A) Use variable names that have at least *some* meaning. B) Space out code, don't jam everything on one line. C) Pick *any* indentation style, but use it *consistently*. D) Always check that you're not exceeding the bounds of the array, but as `n` is given as just a pointer, who knows what's safe here. Maybe you need a `size` argument? – tadman Mar 22 '23 at 19:09
  • Values like `5.22851e-33` are often a sign of something that's basically but *not quite* zero, so it could be the result of some floating point operation that should be zero, but is, as floating point tends to be, a close approximation of it instead. Or it could be uninitialized junk. Where `n` comes from is not clear, so can't say for sure. – tadman Mar 22 '23 at 19:12
  • you've corrupted your stack, most likely by writing outside the bounds of a stack allocated array (presumably `n` is allocated on the stack?). Please show a [mre] – Alan Birtles Mar 22 '23 at 20:08

0 Answers0