【发布时间】:2021-01-13 10:43:27
【问题描述】:
编辑:澄清一下,我在一个 指针数组之后,类型为 Point3d 结构。
我搞砸了一些看起来很简单的事情。我在这里阅读了几篇关于动态分配数组的帖子,但我仍然看不出我哪里出错了。
在下面的代码中,我试图创建一个动态分配的 Point3d 结构指针数组。就这样。但是我搞砸了内存分配(valgrind 报告丢失了 40 个字节等),并且当多次重新分配数组时(ALLOC_COUNT > 1)它在释放时崩溃。我哪里做错了?
我只针对 C99。在 Windows 上执行此操作,CLion 在 WSL 上使用 valgrind。
完整的程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct Point3d_t {
double X;
double Y;
double Z;
} Point3d;
size_t increment_size = 0;
size_t vertex_count = 0;
size_t current_size = 0;
void *destructVertices(Point3d **vertices) {
if (vertices != NULL && ((current_size > 0) || (vertex_count > 0))) {
for (int i = 0; i < current_size; ++i) {
free(vertices[i]);
vertices[i] = NULL;
}
}
return NULL;
}
size_t allocateVertices(Point3d **vertices) {
const size_t new_size = current_size + 1 + increment_size;
Point3d **expanded_items = realloc(*vertices, new_size * sizeof(Point3d *));
if (!expanded_items) { // Allocation failed.
free(*vertices); fprintf(stderr, "RIL: Error reallocating lines array\n");
expanded_items = NULL; exit(0);
}
else if (expanded_items == vertices) {
expanded_items = NULL; // Same mem addr, no need to change
}
else {
vertices = expanded_items; // mem allocated to new address, point there
}
current_size = new_size;
return current_size;
}
/// returning the last item count, which can also be interpreted
/// as true (>0) or false (0) by the caller
size_t addVertex(Point3d point, Point3d **vertices) {
if (vertex_count == current_size) {
if (!allocateVertices(vertices)) return 0;
}
Point3d* p = malloc(sizeof(Point3d));
if (!p) exit(99);
p->X = point.X;
p->Y = point.Y;
p->Z = point.Z;
vertices[vertex_count] = p;
vertex_count += 1;
return vertex_count; // last item count
}
Point3d *m_vertices[1];
将 ALLOC_COUNT 增加到大于 1 的值(导致重新分配)将在解除分配时崩溃。
#define PT_COUNT 4
#define ALLOC_COUNT 1
int main() {
increment_size = PT_COUNT;
current_size = 0;
vertex_count = 0;
printf("Size of Point3d = %zu\n", sizeof(Point3d)); // fake error
printf("Size of *Point3d = %zu\n", sizeof(Point3d *)); // fake error
printf("Size of **m_vertices = %zu\n", sizeof(m_vertices)); // fake error
printf("Size of *m_vertices = %zu\n", sizeof(*m_vertices)); // fake error
printf("Size of *m_vertices[0] = %zu\n", sizeof(*m_vertices[0])); // fake error
printf("---------------------------\n"); // fake error
m_vertices[0] = NULL; //malloc(sizeof(Point3d*));
// new points
for (int i = 0; i < (PT_COUNT * ALLOC_COUNT); ++i) {
Point3d p;
p.X = 1.0 + (i * 0.001);
p.Y = 2.0 + (i * 0.001);
p.Z = 3.0 + (i * 0.001);
const size_t n = addVertex(p, m_vertices);
if (!n) exit(1);
}
printf("vertices.Capacity = %zu\n", current_size);
printf("vertices.Count = %zu\n", vertex_count);
destructVertices(m_vertices);
//free(*m_vertices);
return 0;
}
【问题讨论】:
标签: c memory-leaks