c - 我该怎么做才能导致 realloc 停止工作?

标签 c malloc realloc

这是一个作业。做旧的银行应用程序。我正在尝试使用 malloc 和 realloc 创建一个动态数组,因此它为每个创建的帐户提供了 1 个以上的空间。这只是一个测试,所以根本不完整。 当我运行它时,它会询问我输入的名字、姓氏和年龄,然后在第二遍时它会直接跳过名字并直接进入第二个名字。因为 realloc 不起作用。我什至注释掉了 realloc 语句,结果是一样的。我想也许是因为我没有输入 char 数组中允许的完整 15 个字符,编译器会看到剩余的一些内存,认为这对于 2 x 15 元素数组来说不够,但对于一加 3 元素数组来说足够了。与 int scanf 的结果相同(注释掉)。但这并不能解释为什么我可以索引 1如果 realloc 没有创建一个。也无法调试,GDB 一直说 Dwarf Error:编译单元头中的版本错误(是 4,应该是 2)eclipse。

struct account{
    char firstName[15];
    char lastName[15];
    char age[3];
};
void assign(struct account* test, int count){
    printf("enter first name \n");
    fgets(test->firstName, 15, stdin);
    printf("enter lastName\n");
    fgets(test->lastName, 15, stdin);
    printf("enter age\n");
    //scanf("%d", &test->age);
    fgets(test->age, 3, stdin);
}
int main(void){
    struct account * test = (struct account*)malloc(sizeof(struct account));
    int count = 0;

    assign(&test[count], count);
    count++;

    test = realloc(test, (sizeof(struct account) + count + 2));


    assign(&test[count], count);
    count++;


    printf("%s\n", test[0].firstName);
    printf("%s\n", test[0].lastName);
    printf("%s\n", test[0].age);
    printf("%s\n", test[1].firstName);
    printf("%s\n", test[1].lastName);
    printf("%s\n", test[1].age);
    while(1);
    return 0;
}

Output

我之前在早期草稿中发布了类似的问题,但事实证明问题不是参数问题

最佳答案

查看realloc的手册页:

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to mal‐ loc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), cal‐ loc(), or realloc(). If the area pointed to was moved, a free(ptr) is done.

很明显,realloc 期望第二个参数是字节而不是整数值。

这条语句:test = realloc(test, (sizeof(struct account) + count + 2));不符合逻辑,因为count不是精确计算的字节值。 明确地说,您想要做的是分配更多空间。所以你可以这样做: test = realloc(test, sizeof(struct account) * 2);

一次又一次地调用 realloc 也很糟糕,就像您在代码中执行的那样。您可以设置更大的容量,例如20,假设其结构如下:

if(count == capacity){
    test = realloc(test, sizeof(struct account) * 2);
    capacity = capacity * 2;
}
else{
    ++count;
    /*keep adding*/
}

关于c - 我该怎么做才能导致 realloc 停止工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859752/

相关文章:

c++ - 将字符串写入和读取二进制文件 C++

c - realloc 后奇怪的字符

c - 为什么当我第二次运行循环时该程序会崩溃?

c - 使用三维动态矩阵时的分割错误

c++ - malloc() 和 free() 是如何工作的?

c - 重新分配内存在 c 中不起作用

c - 动态多维数组重新分配

c - 为什么使用 FileTimeToSystemTime() 时程序崩溃?

c - 使用 FFMPEG 从 IP 摄像机读取 RTCP 数据包

c - 实现 4.1.2 及更早版本的 GCC cas 功能