我有这个功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct adress Adress;
struct adress {char *num; char *street; char *namestreet; char *city; char *postal;};
int main(void) {
int n = 0;
int i;
struct adress *Adress;
FILE *f = fopen("/home/file.txt","r");
if (!f) {
printf("Impossible to open file\n");
return 1;
}
char line[256];
while (fgets(line,256,f)) {
if (n == 0) {
Adress = malloc(sizeof(struct adress)*(n+1));
}
Adress[n].num = malloc( 256*sizeof( char));
Adress[n].street = malloc( 256*sizeof( char));
Adress[n].namestreet = malloc( 256*sizeof( char));
Adress[n].city = malloc( 256*sizeof( char));
Adress[n].postal = malloc( 256*sizeof( char));
fscanf( f , "%s %s %s %s %s", Adress[n].num, Adress[n].street, Adress[n].namestreet, Adress[n].city ,Adress[n].postal);
n++;
}
for (i = 0; i < n; i++)
{
printf("\nNum : %s \n", Adress[i].num);
printf("\nStreet : %s \n", Adress[i].street);
printf("\nStreet Name :%s \n", Adress[i].namestreet);
printf("\nCity :%s \n", Adress[i].city);
printf("\nPostal Code : %s \n", Adress[i].postal);
}
fclose(f);
return 0;
}
当我尝试编译程序时,我收到以下错误:
*检测到glibc * ./myprog:损坏的双链表:0x0000000001cd6240
我做错了什么?
之前有没有人遇到过这类错误?
答案 0 :(得分:1)
您只为一个struct adress
分配了足够的空间,如果您读取多行,您将在Adress
指向的数组末尾之外写入并破坏堆。随后对malloc
的调用会检测到此消息并中止消息:./myprog: corrupted double-linked list: 0x0000000001cd6240
。
初始化Adress
至NULL
:
struct adress *Adress = NULL;
并更改以下3行:
if (n == 0) {
Adress = malloc(sizeof(struct adress)*(n+1));
}
到
Adress = realloc(Adress, sizeof(struct adress)*(n+1));
if (!Adress) {
printf("out of memory\n");
exit(1);
}
答案 1 :(得分:0)
你的程序有问题,并且损坏了处理你内存的libc链表。
lib c将“私有”数据存储在您分配的内存块中。
通常会有一个标题:
struct hdr
{
size_t size; /* Exact size requested by user. */
unsigned long int magic; /* Magic number to check header integrity. */
struct hdr *prev;
struct hdr *next;
__ptr_t block; /* Real block allocated, for memalign. */
unsigned long int magic2; /* Extra, keeps us doubleword aligned. */
};
如果其中一个魔法被代码中的缓冲区溢出破坏,则会出现此类错误(因为libc可以发现其结构已损坏)