gpt4 book ai didi

编译器提示 '' *** glibc 检测到 *** ./myprog : corrupted double-linked list: 0x0000000001cd6240 *** ''

转载 作者:行者123 更新时间:2023-11-30 15:14:26 25 4
gpt4 key购买 nike

我有这个功能:

#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 detected * ./myprog: corrupted double-linked list: 0x0000000001cd6240

我做错了什么?

以前有人遇到过这种类型的错误吗?

最佳答案

您只为一个struct adress分配足够的空间,如果您读取超过一行,您将写入超出Adress指向的数组末尾并损坏堆。随后对 malloc 的调用会检测到这一点并中止,并显示以下消息:./myprog:损坏的双链表:0x0000000001cd6240

地址初始化为NULL:

    struct adress *Adress = NULL;

并更改这三行:

    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);
}

关于编译器提示 '' *** glibc 检测到 *** ./myprog : corrupted double-linked list: 0x0000000001cd6240 *** '' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34052950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com