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

时间:2017-10-18 19:03:25

标签: c arrays c99

我写了一个小程序来说明我遇到的问题。该程序应将“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)

2 个答案:

答案 0 :(得分:1)

您将outputs传递给driverFunc作为值:

driverFunc(outputs, &sizeOfOutput);

它的值将传递给函数但不返回。所以,当你在:

中使用它时
printf("Captured output: %s\n", outputs[0]);

outputs仍然没有初始化。

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

driverFunc(&outputs, &sizeOfOutput);

或者只是将其退回:

outputs = driverFunc(&sizeOfOutput);

答案 1 :(得分:1)

如果要更改main

中声明的指针outputs的值
char ** outputs;

在函数中,函数应该通过引用间接通过指针除外。

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

int driverFunc(char *** output, int * sizeOfOutput);

并调用

driverFunc( &outputs, &sizeOfOutput);

使用函数strncpy

strncpy(output[0], buff, BUFFER_SIZE-1);

没有多大意义。使用strcpy

更简单
strcpy( output[0], buff );

如果重新分配失败

 output = realloc(output, (rows+1) * sizeof(char *));

指针output的先前值将丢失。因此,您需要使用中间变量来重新分配内存,并检查调用后它的值是否等于NULL。

变量sizeOfOutput应设置为

*sizeOfOutput = rows + 1;

在main中你应该释放函数中所有已分配的内存。