繁体   English   中英

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

[英]Segmentation fault upon reading from an array

我写了一个小程序来说明我遇到的问题。 该程序应将“ buff [200]”的内容复制到数组“输出”的第一个位置。 执行完复制后,一旦尝试访问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)

您正在将outputs作为值传递到driverFunc

driverFunc(outputs, &sizeOfOutput);

它的值将传递给函数,但不会返回。 因此,当您将其用于:

printf("Captured output: %s\n", outputs[0]);

outputs仍未初始化。

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

driverFunc(&outputs, &sizeOfOutput);

或只返回它:

outputs = driverFunc(&sizeOfOutput);

如果要更改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;

首先,您应该释放函数中所有分配的内存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM