【发布时间】:2017-09-26 21:24:42
【问题描述】:
我正在编写一个代码,它将一个文本文件读入最大 1024 字节的内存块。为此,我正在创建一个包含 1016 字节数据和指向前一个节点的指针的链表。我的代码完美执行,动态分配和使用数据,以及完美链接。当它必须创建第四个节点时,问题就出现了。 当我手动增加 malloc 大小(例如将其设置为 1200)时,它会在崩溃之前创建 48 个节点,这表明结构大小会增加。但是当我打印 sizeof(*memory) 或 sizeof(struct Chunk) 时,大小保持 1024 字节。
由于我使用 malloc 的行导致以下错误:
malloc.c:2392: sysmalloc: 断言`(old_top == initial_top (av) && 旧尺寸 == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' 失败。 中止(核心转储)
我的代码如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char **argv) {
// declare variables
int const CHUNK_SIZE = 1024;
int chunk_index = 0;
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;
// check if the amount of arguments is as expected
if (argc!=2) {
printf("Usage: reverse <filename>\n");
return -1;
}
// check if the file can be opened
FILE *fp;
fp = fopen(argv[1], "r");
if (fp==0) {
printf("Cannot open file!\n");
return -1;
}
// start program
do {
memory->data[chunk_index] = fgetc(fp);
chunk_index++;
if ( chunk_index*sizeof(int) > CHUNK_SIZE-sizeof(struct Chunk*) ) {
temp = (struct Chunk *)malloc(CHUNK_SIZE);
temp->previous = memory;
memory = temp;
}
}
while(memory->data[(chunk_index-1)]!=EOF && chunk_index<CHUNK_SIZE-sizeof(char*));
}
【问题讨论】:
-
你确定
malloc(CHUNK_SIZE);要这样做吗? -
“我的代码执行完美”是一个大胆的声明!
-
gcc sez
warning: a member of a structure or union cannot have a variably modified type。您的代码无效。 -
你为什么要设置
data[]的大小这么复杂?为什么不直接说int data[DATA_SIZE],以获得DATA_SIZE的适当值? -
另外,如果要存储字符,为什么
data是int的数组? (是的,如果它是char的数组,那么您将很难可靠地测试 EOF,但是有比将整个数组设为int的数组更好的方法来解决这个问题。)