I wrote a C program in Clion, using dynamic memory allocation. I noticed sometimes gave different output for the same input. At first I tought there was a problem with Clion (I was using it for the first time), but I also ran the program from the windows command line, and the same bug occured.
main.c
#include "main.h"
int main()
{
int n;
scanf("%d", &n);
int *t = (int*)calloc(n, sizeof(int));
for (int i = 0; i < n; ++i) {
scanf("%d", &t[i]);
}
int p = peak(t, n);
printf( p == -1 ? "No peak" : "Peak %d, position %d", t[p], p );
free(t);
return 0;
}
main.h
//
// Created by Botond on 2021. 02. 18..
//
#ifndef EXTRA_MAIN_H
#define EXTRA_MAIN_H
#include <stdio.h>
#include <stdlib.h>
int peak( int *t, int n)
{
int p = -1, i = 0;
while(t[i] <= t[i+1])
i++;
p = i;
while(t[i] >= t[i+1])
i++;
if(i == n + 1)
return p;
else
return -1;
}
#endif //EXTRA_MAIN_H