c - 使用带有动态数组的结构指针的内存分配 (realloc) 时出错

标签 c function memory-management std

vector_int.h是一个自制的动态数组( vector )结构的头文件。

test.c 是一个测试程序。

所有代码如下:

vector_int.h:

#include <stdio.h>

typedef struct 
{
    long int len; // Length
    int *array;   // Dynamic Array
} IntVector; 

void ResizeIntVector(IntVector *vector, int size) // Resizing of vector
{
    realloc(vector->array, size * sizeof(int));
    vector->len = size; // Changing of length variable
}

void SetIntVectorCell(IntVector *vector, unsigned int cell_number, int cell_value) // Put cell_value in array[cell_number]
{
    if (cell_number >= vector->len)
        ResizeVectorInt(&vector, cell_number); // Grow size of memory if it's not enough

    vector->array[cell_number] = cell_value;
}

测试.c:

#include "vector_int.h"
#include <stdio.h>

int main()
{
    IntVector vector;

    int n;
    scanf("%d", &n);

    int i;
    for (i = 0; i < n; i++) // testing
    {
        SetIntVectorCell(&vector, i, i);
        printf("%d ", vector.array[i]);
    }

    return 0;       
}

日志:

1   0   D:\Work\Raspberry Pi\test.c In file included from D:\Work\Raspberry Pi\test.c
        D:\Work\Raspberry Pi\vector_int.h   In function 'ResizeIntVector':
11  2   D:\Work\Raspberry Pi\vector_int.h   [Warning] incompatible implicit declaration of built-in function 'realloc' [enabled by default]
            [Linker error] C:\Users\ALEXAN~1\AppData\Local\Temp\cccFKqxs.o:test.c:(.text+0x4a): undefined reference to `ResizeVectorInt'
            collect2: ld returned 1 exit status

我认为使用 realloc 函数有错误,但我认为我做对了。 请帮我找出一个或多个错误。

最佳答案

你有几个问题:

  • implicit declaration/realloc 问题是因为您需要为realloc 签名包含stdlib.h。如果没有函数签名,编译器将对您的函数参数和返回值做出一些假设,然后在链接期间,如果这些假设与实际的函数实现不匹配,链接器会提示这一点。

  • 您正在向 realloc 传递一个尚未初始化的地址。这是自讨苦吃。在使用你的 vector 变量之前,做一些初始化:

    vector->array = NULL;
    vector->len = 0;
    
  • 此外,您对 realloc 的使用是不正确的:它不会更改您给它的实际指针,只会更改指向的内存块的大小。您需要自己重新分配指针。请注意,realloc 可以在失败时返回 NULL,因此请执行以下操作:

    tmp = realloc(vector->array, size * sizeof(int));
    
    if (tmp != NULL)
    {
        vector->array = tmp;
        vector->len = size; // Changing of length variable
    }
    else handleAllocError();
    
  • 最后,不要在标题中定义您的函数。这会起作用,但最好有一个实现文件 vector_int.c 来定义 header 中声明的函数。

关于c - 使用带有动态数组的结构指针的内存分配 (realloc) 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11802707/

相关文章:

c - 初始化从整数生成指针而不进行强制转换 - C

c - 为什么下面的代码没有给出双重释放错误?

Python Pandas - 重命名列后出现段错误?

Java String 对象没有按时收集垃圾

c++ - 当操作系统无法分配内存时,使用 STL 的应用程序是否应该容易发生内存泄漏?

c++ - 使用 C++ 进行面向对象设计中的内存管理

c - 如果函数写在主函数之上,则不需要函数声明。为什么?

c - 如何将一个字节写入特定内存地址的寄存器?

c - 了解 x86 IA32 程序集中函数调用的前/后汇编代码

Bash:导出函数以在 xargs 中使用