C 从数组读取时出现分段错误

C 从数组读取时出现分段错误,c,arrays,c99,C,Arrays,C99,我写了一个小程序来说明我遇到的一个问题。该程序应将“buff[200]”的内容复制到数组“output”的第一个位置。在执行复制之后,我读取了几次该值,以查看当我尝试访问driverFunc范围之外的数据时,由于出现分段错误,该值何时消失。我知道我正在创建一个包含6个位置的数组,但只向第一个位置添加数据,这最终将位于填充输出数组其余部分的循环中。我的用例还需要能够扩展此阵列的大小 #include <stdlib.h> #include <stdio.h> #includ

我写了一个小程序来说明我遇到的一个问题。该程序应将“buff[200]”的内容复制到数组“output”的第一个位置。在执行复制之后,我读取了几次该值,以查看当我尝试访问driverFunc范围之外的数据时,由于出现分段错误,该值何时消失。我知道我正在创建一个包含6个位置的数组,但只向第一个位置添加数据,这最终将位于填充输出数组其余部分的循环中。我的用例还需要能够扩展此阵列的大小

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 1035
int driverFunc(char ** output, int * sizeOfOutput) {
  int rows = 5;
  char buff[200] = "hello world";

  output = malloc(rows * sizeof(char *));  //malloc row space
  //malloc column space
  for (int i = 0; i < rows; i ++) {
    output[i] = malloc(BUFFER_SIZE * sizeof(char));
  }

  //copy contents of buff into first position of output
  strncpy(output[0], buff, BUFFER_SIZE-1);
  printf("Output 1: %s\n", output[0]); //verify that it's there

  //resize the array
  output = realloc(output, (rows+1) * sizeof(char *));
  //allocate space for the new entry
  output[rows] = malloc(BUFFER_SIZE * sizeof(char));
  *sizeOfOutput = rows;

  //verify that it's still there
  printf("Output 2: %s\n", output[0]);
  return 0;
}
int main() {
  char ** outputs;
  int sizeOfOutput;
  driverFunc(outputs, &sizeOfOutput);
  //verify that we can do useful things with our output
  printf("Reported size: %d\n", sizeOfOutput);
  printf("Captured output: %s\n", outputs[0]);  //segfault
}
收到的输出:

Output 1: hello world
Output 2: hello world
Reported size: 5
Captured output: hello world
Output 1: hello world
Output 2: hello world
Reported size: 5
Segmentation fault (core dumped)

您正在将
输出作为值传递到
driverFunc

driverFunc(outputs, &sizeOfOutput);
其值将传递给函数,但不会返回。因此,当您在中使用它时:

printf("Captured output: %s\n", outputs[0]);
输出
仍未初始化

您需要将其作为引用传递(并相应地更改
driverFunc
):

或者直接退回:

outputs = driverFunc(&sizeOfOutput);

如果要更改main中声明的指针
输出值

char ** outputs;
在一个函数中,则该函数应该通过引用除去间接通过指针的指针

因此,函数应该至少声明为

int driverFunc(char *** output, int * sizeOfOutput);
打电话给我

driverFunc( &outputs, &sizeOfOutput);
使用函数
strncpy

strncpy(output[0], buff, BUFFER_SIZE-1);
strcpy( output[0], buff );
这没有多大意义。使用strcpy

strncpy(output[0], buff, BUFFER_SIZE-1);
strcpy( output[0], buff );
如果重新分配失败

 output = realloc(output, (rows+1) * sizeof(char *));
指针
输出的上一个值将丢失。因此,您需要使用一个中间变量来重新分配内存,并检查调用后它的值是否等于NULL

变量
sizeOfOutput
应设置为

*sizeOfOutput = rows + 1;

基本上,您应该释放函数中所有分配的内存。

strcpy(输出[0],缓冲区大小-1)
但是strcpy只接受两个参数。这意味着strncpy函数
driverFunc
不会更改传递给它的变量
输出的值。在
main
中,它仍然是一个未初始化的变量。如何修改它以更改函数中的值?按指针传递。