I'm writing a program in c and I encountered an error message:
Program terminated with signal SIGSEGV, Segmentation fault.
At that time I ran that program using dev-c++ on my system then the program ran successfully until it returned:
[Warning] function returns address of local variable [enabled by default]
I am not able to understand what is happening.
Here's my program:
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int* getRecord(int s_size, int* s, int *result_size){
int i = 0, heigh = s[0], low = s[0], heigh_count = 0, low_count = 0, a[2];
for(i = 1; i < s_size; i++){
if(s[i] > heigh){
heigh_count++;
heigh = s[i];
}
if(s[i] < low){
low_count++;
low = s[i];
}
}
*result_size = 2;
a[0] = heigh_count;
a[1] = low_count;
return a;
}
int main() {
int n;
scanf("%d",&n);
int *s = malloc(sizeof(int) * n);
for(int s_i = 0; s_i < n; s_i++){
scanf("%d",&s[s_i]);
}
int result_size;
int* result = getRecord(n, s, &result_size);
for(int i = 0; i < result_size; i++) {
if (i) {
printf(" ");
}
printf("%d", result[i]);
}
puts("");
return 0;
}
Input
9
10 5 20 20 4 5 2 25 1
Output
2 4
Error log
GDB trace:
Reading symbols from solution...done.
[New LWP 17778]
Core was generated by `solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x000000000040065d in printf (__fmt=0x4008a7 "%d")
at /usr/include/x86_64-linux-gnu/bits/stdio2.h:104
104 return __printf_chk (__USE_FORTIFY_LEVEL - 1, __fmt, __va_arg_pack ());
#0 0x000000000040065d in printf (__fmt=0x4008a7 "%d")
at /usr/include/x86_64-linux-gnu/bits/stdio2.h:104
#1 main () at solution.c:41