删除资源时,编程最终崩溃。伪通用动态数组列表的C实现
我已经用 C 实现了一个针对原始类型的伪通用动态数组。它采用枚举常量作为每种类型的标识符 - INT
、LONG_INT
、DECIMAL
、CHAR
。主结构list
有一个成员_assets
,它是一个void
指针(具有抽象级别)。这个 void 指针在 C 文件实现中被类型转换为另一个结构(这是容器的主要内部工作)。我测试了所有类型的列表,它工作得很好。当我创建 2 个列表,执行一些操作,然后按照创建顺序同时删除这两个列表时,出现了问题。它给了我一个错误:- 检测到严重错误 c0000374
;并显示无法打开“free-base.cpp”
。删除通过 free_assets
方法进行。当我在使用第二个列表对象之前删除第一个列表对象时,这两个列表工作得很好,这很不寻常,因为它们是两个不同的对象。
primitive_list.h
#ifndef PRIMITIVE_LIST_H
#define PRIMITIVE_LIST_H
typedef enum { INT, LONG_INT, DECIMAL, CHAR } list_types;
typedef struct
{
void *_assets;
} list;
list *create_list(list_types type);
void push(list **self, ...);
void pop(list **self);
void*at(list *self, const int index);
int empty(list *self);
unsigned length(list *self);
void print_list(list *self);
void free_assets(list **self);
#endif
primitive_list.c
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "primitive_list.h"
typedef struct
{
int capacity;
int size;
void *arr;
list_types type;
int empty;
} _list;
_list _create_list(list_types type)
{
_list res;
res.type = type;
res.capacity = 1;
res.size = 0;
res.empty = 1;
return res;
}
void _alloc(_list *self)
{
switch ((self)->type)
{
int n = (self)->capacity;
case INT:
(self)->arr = calloc(n, sizeof(int));
break;
case LONG_INT:
(self)->arr = calloc(n, sizeof(long long));
break;
case DECIMAL:
(self)->arr = calloc(n, sizeof(double));
break;
case CHAR:
(self)->arr = calloc(n, sizeof(char));
break;
}
return;
}
void _realloc(_list *self, size_t Buffer_size)
{
(self)->capacity = Buffer_size;
list_types type = (self)->type;
int n = (self)->capacity;
int s = (self)->size;
if (type == INT) {
int *new_array = (int *)calloc(n, sizeof(int));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((int *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
} else if (type == LONG_INT) {
long long *new_array = (long long *)calloc(n, sizeof(long long));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((long long *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
} else if (type == DECIMAL) {
double *new_array = (double *)calloc(n, sizeof(double));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((double *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
} else if (type == CHAR) {
char *new_array = (char *)calloc(n, sizeof(char));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((char *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
}
return;
}
void _push(_list *self, ...)
{
if ((self)->empty)
{
(self)->empty = 0;
_alloc(self);
}
if ((self)->size == (self)->capacity)
_realloc(self, (self)->capacity * 2);
va_list arg;
va_start(arg, self);
switch ((self)->type)
{
case INT:
((int *)(self)->arr)[(self)->size] = va_arg(arg, int);
break;
case LONG_INT:
((long long *)(self)->arr)[(self)->size] = va_arg(arg, long long);
break;
case DECIMAL:
((double *)(self)->arr)[(self)->size] = va_arg(arg, double);
break;
case CHAR:
((char *)(self)->arr)[(self)->size] =(char)va_arg(arg, int);
break;
}
(self)->size++;
va_end(arg);
return;
}
void _pop(_list *self)
{
if ((self)->empty)
{
fprintf(stderr,"List is empty!\n");
return;
}
(self)->size--;
return;
}
void *_at(_list *self, const int index)
{
void *res;
switch ((self)->type)
{
case INT:
res = malloc(sizeof(int));
*((int *)res) = ((int *)(self)->arr)[index];
break;
case LONG_INT:
res = malloc(sizeof(long long));
*((long long *)res) = ((long long *)(self)->arr)[index];
break;
case DECIMAL:
res = malloc(sizeof(double));
*((double *)res) = ((double *)(self)->arr)[index];
break;
case CHAR:
res = malloc(sizeof(char));
*((char *)res) = ((char *)(self)->arr)[index];
break;
}
return res;
}
int _empty(_list *self)
{
return self->empty;
}
unsigned _length(_list *self)
{
return self->size;
}
void _print_list(_list *self)
{
for (size_t i = 0; i < self->size; i++)
{
switch(self->type)
{
case INT:
printf("%d ", ((int *)self->arr)[i]);
break;
case LONG_INT:
printf("%lld ", ((long long *)self->arr)[i]);
break;
case DECIMAL:
printf("%lf ", ((double *)self->arr)[i]);
break;
case CHAR:
printf("%c ",((char*)self->arr)[i]);
break;
}
}
printf("\n");
return;
}
void _free_list(_list *self)
{
free((self)->arr);
}
list *create_list(list_types type)
{
static list res;
_list obj = _create_list(type);
res._assets = malloc(sizeof(_list));
*((_list*)res._assets) = obj;
return &res;
}
void push(list **self, ...)
{
va_list arg;
va_start(arg, self);
switch (((_list *)(*self)->_assets)->type)
{
case INT:
_push(((_list *)(*self)->_assets), va_arg(arg, int));
break;
case LONG_INT:
_push(((_list *)(*self)->_assets), va_arg(arg, long long));
break;
case DECIMAL:
_push(((_list *)(*self)->_assets), va_arg(arg, double));
break;
case CHAR:
_push(((_list *)(*self)->_assets), (char)va_arg(arg, int));
break;
}
va_end(arg);
return;
}
void pop(list **self)
{
_pop(((_list *)(*self)->_assets));
return;
}
void *at(list *self, const int index)
{
return _at((_list *)self->_assets, index);
}
int empty(list *self)
{
return _empty((_list *)self->_assets);
}
unsigned length(list *self)
{
return _length((_list *)self->_assets);
}
void print_list(list *self)
{
_print_list((_list *)self->_assets);
return;
}
void free_assets(list **self)
{
_free_list(((_list *)(*self)->_assets));
free((*self)->_assets);
}
test.c
#include <stdio.h>
#include <stdlib.h>
#include "primitive_list.h"
int main(int argc, char **argv)
{
//Decimal List
list *nums = create_list(DECIMAL);
push(&nums, 3.14159);
push(&nums, 6.25);
push(&nums, 22.2222);
push(&nums, 100.0);
print_list(nums);
//Character list
list *chars = create_list(CHAR);
push(&chars, 'A');
push(&chars, 'w');
push(&chars, 'Z');
push(&chars, 'q');
push(&chars, 'P');
print_list(chars);
//Code causing the error
free_assets(&nums);
free_assets(&chars);
return 0;
}
I have implemented a pseudo-generic dynamic array in C, for primitive types. It takes enum constants as identifier for each type- INT
, LONG_INT
, DECIMAL
, CHAR
. The main struct list
has a member _assets
, which is a void
pointer (to have a level of abstraction). This void
pointer is type-casted to another struct (which is the main internal working of the container) in the C file implementation. I tested the list with all the types, and it worked perfectly fine. The problem arose when I created 2 lists, performed some operations, and then deleted the both lists together in the same order they were created. It gives me an error:- Critical error detected c0000374
; and says, unable to open 'free-base.cpp'
. The deletion takes play through the free_assets
method. The 2 lists work perfectly fine when I delete the first list object before using the second list object, which is quiet unusual, since they are 2 different objects.
primitive_list.h
#ifndef PRIMITIVE_LIST_H
#define PRIMITIVE_LIST_H
typedef enum { INT, LONG_INT, DECIMAL, CHAR } list_types;
typedef struct
{
void *_assets;
} list;
list *create_list(list_types type);
void push(list **self, ...);
void pop(list **self);
void*at(list *self, const int index);
int empty(list *self);
unsigned length(list *self);
void print_list(list *self);
void free_assets(list **self);
#endif
primitive_list.c
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include "primitive_list.h"
typedef struct
{
int capacity;
int size;
void *arr;
list_types type;
int empty;
} _list;
_list _create_list(list_types type)
{
_list res;
res.type = type;
res.capacity = 1;
res.size = 0;
res.empty = 1;
return res;
}
void _alloc(_list *self)
{
switch ((self)->type)
{
int n = (self)->capacity;
case INT:
(self)->arr = calloc(n, sizeof(int));
break;
case LONG_INT:
(self)->arr = calloc(n, sizeof(long long));
break;
case DECIMAL:
(self)->arr = calloc(n, sizeof(double));
break;
case CHAR:
(self)->arr = calloc(n, sizeof(char));
break;
}
return;
}
void _realloc(_list *self, size_t Buffer_size)
{
(self)->capacity = Buffer_size;
list_types type = (self)->type;
int n = (self)->capacity;
int s = (self)->size;
if (type == INT) {
int *new_array = (int *)calloc(n, sizeof(int));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((int *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
} else if (type == LONG_INT) {
long long *new_array = (long long *)calloc(n, sizeof(long long));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((long long *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
} else if (type == DECIMAL) {
double *new_array = (double *)calloc(n, sizeof(double));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((double *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
} else if (type == CHAR) {
char *new_array = (char *)calloc(n, sizeof(char));
for (size_t i = 0; i < s; i++)
{
new_array[i] = ((char *)(self)->arr)[i];
}
free((self)->arr);
(self)->arr = (void *)new_array;
}
return;
}
void _push(_list *self, ...)
{
if ((self)->empty)
{
(self)->empty = 0;
_alloc(self);
}
if ((self)->size == (self)->capacity)
_realloc(self, (self)->capacity * 2);
va_list arg;
va_start(arg, self);
switch ((self)->type)
{
case INT:
((int *)(self)->arr)[(self)->size] = va_arg(arg, int);
break;
case LONG_INT:
((long long *)(self)->arr)[(self)->size] = va_arg(arg, long long);
break;
case DECIMAL:
((double *)(self)->arr)[(self)->size] = va_arg(arg, double);
break;
case CHAR:
((char *)(self)->arr)[(self)->size] =(char)va_arg(arg, int);
break;
}
(self)->size++;
va_end(arg);
return;
}
void _pop(_list *self)
{
if ((self)->empty)
{
fprintf(stderr,"List is empty!\n");
return;
}
(self)->size--;
return;
}
void *_at(_list *self, const int index)
{
void *res;
switch ((self)->type)
{
case INT:
res = malloc(sizeof(int));
*((int *)res) = ((int *)(self)->arr)[index];
break;
case LONG_INT:
res = malloc(sizeof(long long));
*((long long *)res) = ((long long *)(self)->arr)[index];
break;
case DECIMAL:
res = malloc(sizeof(double));
*((double *)res) = ((double *)(self)->arr)[index];
break;
case CHAR:
res = malloc(sizeof(char));
*((char *)res) = ((char *)(self)->arr)[index];
break;
}
return res;
}
int _empty(_list *self)
{
return self->empty;
}
unsigned _length(_list *self)
{
return self->size;
}
void _print_list(_list *self)
{
for (size_t i = 0; i < self->size; i++)
{
switch(self->type)
{
case INT:
printf("%d ", ((int *)self->arr)[i]);
break;
case LONG_INT:
printf("%lld ", ((long long *)self->arr)[i]);
break;
case DECIMAL:
printf("%lf ", ((double *)self->arr)[i]);
break;
case CHAR:
printf("%c ",((char*)self->arr)[i]);
break;
}
}
printf("\n");
return;
}
void _free_list(_list *self)
{
free((self)->arr);
}
list *create_list(list_types type)
{
static list res;
_list obj = _create_list(type);
res._assets = malloc(sizeof(_list));
*((_list*)res._assets) = obj;
return &res;
}
void push(list **self, ...)
{
va_list arg;
va_start(arg, self);
switch (((_list *)(*self)->_assets)->type)
{
case INT:
_push(((_list *)(*self)->_assets), va_arg(arg, int));
break;
case LONG_INT:
_push(((_list *)(*self)->_assets), va_arg(arg, long long));
break;
case DECIMAL:
_push(((_list *)(*self)->_assets), va_arg(arg, double));
break;
case CHAR:
_push(((_list *)(*self)->_assets), (char)va_arg(arg, int));
break;
}
va_end(arg);
return;
}
void pop(list **self)
{
_pop(((_list *)(*self)->_assets));
return;
}
void *at(list *self, const int index)
{
return _at((_list *)self->_assets, index);
}
int empty(list *self)
{
return _empty((_list *)self->_assets);
}
unsigned length(list *self)
{
return _length((_list *)self->_assets);
}
void print_list(list *self)
{
_print_list((_list *)self->_assets);
return;
}
void free_assets(list **self)
{
_free_list(((_list *)(*self)->_assets));
free((*self)->_assets);
}
test.c
#include <stdio.h>
#include <stdlib.h>
#include "primitive_list.h"
int main(int argc, char **argv)
{
//Decimal List
list *nums = create_list(DECIMAL);
push(&nums, 3.14159);
push(&nums, 6.25);
push(&nums, 22.2222);
push(&nums, 100.0);
print_list(nums);
//Character list
list *chars = create_list(CHAR);
push(&chars, 'A');
push(&chars, 'w');
push(&chars, 'Z');
push(&chars, 'q');
push(&chars, 'P');
print_list(chars);
//Code causing the error
free_assets(&nums);
free_assets(&chars);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您这里的代码有点令人困惑,因为您似乎无缘无故地将底层结构埋藏在另一个结构中。您没有理由不能简单地(如果您想将实现细节保持私有)在标头和实现中编写
typedef struct list list;
这样,就必须处理的混乱会少得多使用
_assets
指针;您可以直接直接寻址列表成员,而无需取消引用和强制转换(这毫无必要地令人困惑)。这里的主要问题实际上是由于
create_list
函数的实现导致内存管理不良。具体来说,这两行:static
关键字在这里的作用是定义一个在该函数的所有调用之间共享的全局变量。也就是说,每次调用create_list
时,res
变量都会设置为与函数上次返回
时相同的值。这就是为什么您可以从此函数返回&res
来获取函数外部的有效指针:res
变量存储在程序的全局内存中,而不是存储在函数的堆栈框架。这个程序有(至少!)两个问题:
list
的指针都是相同的,因此创建的每个list
都会覆盖该对象的内存。 Lastlist
,它不仅会泄漏内存(指向_assets
结构的指针),而且只使最后创建的列表有效。事实上,您的nums
和chars
列表应该与创建chars
时具有完全相同的值。malloc
分配的内存调用free
。因为您从create_list
函数返回真正的全局变量的地址,所以您将返回一个指向操作系统在程序首次加载时创建的内存的指针。您不拥有该内存,并且尝试对其调用free
与您在这里看到的效果完全相同:它会使您的程序崩溃。这两个问题都可以用同样的方式解决:正确管理你的内存。一般来说,如果您想在 C 内存中创建一个结构,您应该使用适当的大小调用
malloc
,初始化新内存的值,并将指向它的指针返回给调用者。这可以在您的情况下实现为:或者,如果您按照我上面的建议更改
list
的布局,只需:Your code here is a bit confusing, as it appears you're burying your underlying structure in another structure for no reason. There's no reason you cannot simply (if you want to keep implementation details private) write
typedef struct list list;
in the header and in your implementation haveThis way, there would be much less confusion about having to deal with the
_assets
pointer; you could simply address the list members directly without a dereference and cast (this is needlessly confusing).Your main issue here is actually due to bad memory management in your
create_list
function due to its implementation. Specifically, these two lines:What the
static
keyword does here is to define a global variable shared between all invocations of this function. That is, every time you callcreate_list
, theres
variable is set to the same value as it was at the lastreturn
from the function. This is why you can return&res
from this function to get a valid pointer outside the function: theres
variable is stored in global memory for your program instead of in the function's stack frame.There are then (at least!) two issues with this program:
list
you create will be the same, so everylist
created will override the memory of the lastlist
, which not only leaks memory (the pointer to the_assets
structure), but makes only the last created list valid. In fact, yournums
andchars
lists should have exactly the same value oneschars
is created.free
on memory you didn't allocate withmalloc
. Because you return the address of a bona-fide global variable from yourcreate_list
function, you're returning a pointer to memory created by the Operating System when your program is first loaded. You DO NOT own this memory, and attempting to callfree
on it has exactly the effect you're seeing here: it will crash your program.Both of these issues can be resolved in the same way: properly manage your memory. Generally, if you want to create a structure in memory in C, you should be calling
malloc
with the proper size, initializing the value of the new memory, and returning the pointer to it back to the caller. This can be implemented in your case as:Or, if you change the layout of
list
as I suggest above, simply:这里有一个问题:
这个函数在
main()
中被调用两次,但返回一个指向静态变量的指针,这意味着每次调用它都会返回相同的地址。因此,当main()
看起来创建指向两个不同列表的指针时,它们实际上是指向单个列表的指针,即static list res
。You have a problem here:
This function is called twice in
main()
, but returns a pointer to a static variable, meaning it will return the same address every time it is called. So whenmain()
appears to create pointers to two different lists, they are actually pointers to a single list, namelystatic list res
.您的代码中存在多个问题:
向用户隐藏实现不需要像发布的那样间接,您可以只声明
struct list
而无需定义。create_list
返回一个static
对象的地址,毫不奇怪地释放它会产生未定义的行为,更不用说所有列表对象实际上都是同一个对象。_alloc()
中switch
块开头的行int n = (self)->capacity;
永远不会被执行。将此行移至switch
语句之前。您不应使用以
_
开头的标识符。括号
(self)
毫无用处且令人困惑。这是一个简化版本:
primitive_list.h:
primitive_list.c:
test.c:
输出:
There are multiple problems in your code:
hiding the implementation from the user does not require an indirect as posted, you can just declare the
struct list
without a definition.create_list
returns the address of astatic
object, no surprise freeing this has undefined behavior, not to mention the fact that all list objects objects are actually the same object.the line
int n = (self)->capacity;
at the beginning of theswitch
block in_alloc()
is never executed. Move this line before theswitch
statement.you should not use identifiers starting with a
_
.parenthesizing
(self)
is useless and confusing.Here is a simplified version:
primitive_list.h:
primitive_list.c:
test.c:
Output: