C: 段错误 11 仅在终端中,不在调试器中

C: Segmentation fault 11 only in terminal, not in debugger

我正在制作一个读取文件的程序,一点一点地反转它并将结果存储在一个新文件中,而不分配大于 1kb 的块。当我 运行 它在终端中时,它创建文件但不写入它,而是崩溃并给出分段错误 11。当我尝试使用 lldb 调试它时,整个代码 运行s没有任何问题。我的终端是否遵循与 lldb 不同的分配规则?我该如何解决这个问题?

我已经 运行 包含大文件和小文件的代码,但即使是几乎为空的 txt 文件,它也会崩溃。 我正在 运行宁 osx 10.10.5 与 lldb-340.4.119

int const CHUNK_SIZE = 1024;
int chunk_index = 0;
int character;
char new_filename[] = "output";

struct Chunk {
  struct Chunk *previous;
  int data[(CHUNK_SIZE-sizeof(struct Chunk*))/sizeof(int)];
};

struct Chunk* memory = (struct Chunk *)malloc(sizeof(struct Chunk));
struct Chunk* temp;

FILE *fp;
fp = fopen(argv[1], "r");

    // read file into memory
character = fgetc(fp);
do {
  memory->data[chunk_index] = character;
  chunk_index++;
  if ( chunk_index*sizeof(int) > CHUNK_SIZE-sizeof(struct Chunk*)){
    chunk_index = 0;
    temp = (struct Chunk *)malloc(sizeof(struct Chunk));
    temp->previous = memory;
    memory = temp;
  }
  character = fgetc(fp);
}
while (character !=EOF);
chunk_index--;
fclose(fp);


    // write to new file
fp = fopen(new_filename, "wb");

do {
  while (chunk_index >=0) {
    printf("%c", memory->data[chunk_index]);
    fprintf(fp, "%c", memory->data[chunk_index]);
    chunk_index--;
  }

  chunk_index = (CHUNK_SIZE-sizeof(struct Chunk*))/sizeof(int);
  temp = memory;
  memory = memory->previous;
  free(temp);
} while(memory!=NULL);

有调试器和没有调试器的 运行 之间的差异可能是由于调试器禁用了 ASLR。这可能会在您尝试调试时隐藏问题。

尝试撤消此操作。 seems 在 LLDB 中应该使用命令

settings set target.disable-aslr false

这应该可以撤消 ASLR 的禁用。在 GDB 中它将是

set disable-randomization off

不要忘记在调试器下重新启动程序(不要重新启动调试器!)以使此设置生效。在 GDB 中是 run 命令,类似的东西应该在 LLDB 中。