c - 从 C 中的函数返回数组 : Segmentation Fault

标签 c arrays segmentation-fault

我正在尝试使用头文件实现一个简单的程序,其中头文件中的函数接受 int数组并返回 int数组也是如此。

header.h :

int* point(int a[]);

header.c :

#include<stdio.h>
#include "header.h"

int* point(int a[])
{
 printf("In the point function\n");
 int array[4],i;
 for(int i=0;i<4;i++)
 {
    printf("%dth Iteration\n",i);
    array[i]=a[i];
 }

return array;
}

test.c :

#include<stdio.h>
#include "header.h"
void main()
{
 int *array,i;
  int a[]={1,2,3,4};
   printf("calling point function\n");
  array=point(a);
  printf("Back in the main function\n");
  for(i=0;i<4;i++)
  {
    //SEGMENTATION FAULT HERE
    printf("%d\n",array[i]);
  }

}

我在 test.c 中的打印循环中遇到段错误.

最佳答案

您不能从函数返回数组。当point()返回时,该函数内的本地数组超出范围。该数组在堆栈上创建,一旦函数完成返回,该数组就会被销毁。与其关联的所有内存都将被丢弃,并且返回的指针指向堆栈上不再存在的位置。您需要在堆上分配一个指针,然后返回该指针。这允许array在您的程序中共享。

而不是:

int array[4];

您需要使用 malloc() 动态分配指针:

int *array = malloc(4 * sizeof(*array)); /* or sizeof(int) */
if (array == NULL) {
    /* handle exit */
}

malloc() allocates requested memory on the heap, and returns a void* pointer to it.

注意: malloc() 不成功时会返回 NULL,因此需要始终进行检查。您还需要free()之前由 malloc() 分配的任何内存。你也don't need to cast return of malloc() .

另一件事需要指出的是在你的程序中使用神奇的数字4。这确实应该使用 sizeof(a)/sizeof(a[0]) 来计算。

您可以在 main() 中将其声明为 size_t 变量:

size_t n = sizeof(a)/sizeof(a[0]);

或者您可以使用宏:

#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))

每次您需要数组的大小时,只需调用 ARRAYSIZE(a) 即可。

关于c - 从 C 中的函数返回数组 : Segmentation Fault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41928056/

相关文章:

c++ - 为什么小数字的答案是错误的?与MPIR

c - 指针数组的初始化

c++ - 如何在指针表示法和数组表示法中循环遍历二维数组

c - unix 守护进程因未知原因停止且没有 coredump

c - 在 Ruby 中运行已编译的 C 文件是否会捕获 C 的 printf()?

java - 使用三重 int 数组

c - 传递给函数的 wchar_t 数组

c - 程序不断崩溃

java - 什么可能导致 JVM 崩溃并显示 SIGSEGV "ClassLoaderData::metaspace_non_null()"

c - 如何在 C 中为两个 for 循环编写 SSE 指令?