gpt4 book ai didi

c - 返回整数指针或数组基地址时出现段错误

转载 作者:行者123 更新时间:2023-11-30 20:20:48 26 4
gpt4 key购买 nike

我正在 中编写程序我遇到了一条错误消息:

Program terminated with signal SIGSEGV, Segmentation fault.

当时我使用 运行该程序在我的系统上,程序成功运行直到返回:

[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

最佳答案

警告

function returns address of local variable

几乎说明了一切。您无法将数组 a 作为 int* 返回。

getRecord() 返回时,

a 被销毁,因此您只剩下 result 持有指向无效数据的指针,您将得到一个尝试访问 result[i] 时出现段错误。

如果您使用 malloca 放在堆上,您可能会没事,但这里仍然存在指针和数组的奇怪混合。

关于c - 返回整数指针或数组基地址时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com