c 로 프로그램을 작성하고 있는데 오류 메시지가 나타납니다.
Program terminated with signal SIGSEGV, Segmentation fault.
그 당시 시스템에서 dev-c ++ 를 사용하여 해당 프로그램을 실행 한 다음 반환 될 때까지 프로그램이 성공적으로 실행되었습니다.
[Warning] function returns address of local variable [enabled by default]
나는 무슨 일이 일어나고 있는지 이해할 수 없습니다.
내 프로그램은 다음과 같습니다.
#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;
}
입력
9
10 5 20 20 4 5 2 25 1
산출
2 4
오류 기록
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
경고
함수는 지역 변수의 주소를 반환합니다.
거의 모든 것을 말합니다. 배열 a
을 int*
.
a
getRecord()
반환 시 파괴 되므로 result
유효하지 않은 데이터에 대한 포인터를 보유하게되며 액세스를 시도 할 때 분할 오류가 발생합니다 result[i]
.
a
를 사용하여 힙에 넣으면 malloc
아마 괜찮을 것입니다. 그러나 여기에는 여전히 포인터와 배열의 이상한 혼합이 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다