[英]Deallocationg char** inside a struct
这个问题类似于我的。
但是没有为我提供解决方案。
这只是用于测试和更好理解的简化代码。
我知道这段代码不在乎malloc函数之后的问题。
该代码用于将单词保存在用作数组的char **存储区中的名为List的结构中。
创建列表并添加项目效果很好。
但是删除列表会带来问题。
这是代码:
声明清单:
typedef struct {
char** storage;
} List;
主要:
int main(){
int size = 2;
List* list;
list = new_list(2);
add(list, "Hello", 0);
add(list, "World", 1);
printf("\nlist->storage[0]: %s", list->storage[0]);
printf("\nlist->storage[1]: %s", list->storage[1]);
delete_list(&list,size);
return 0;
}
新建一个列表:
List* new_list(size) {
List* listptr = malloc(sizeof(List));
listptr->storage = (char**)malloc(size * sizeof(char));
return listptr;
}
在列表中添加一个字符串:
void add(List* list, char* string, int pos) {
list->storage[pos] = (char*)malloc(strlen(string) * sizeof(char));
list->storage[pos] = string;
}
删除所有成员的列表:
void delete_list(List** list, int size) {
int a = 0;
for (a = 0; a < size; a++)
free((*list)->storage[a]);
free((*list)->storage);
free(*list);
}
在这里,在for循环中,在“ free((* list)-> storage [a])”行出现错误。
目的是删除每个分配的字符串。
如果列表没有成员,则代码不会在for循环中运行,并且'delte_list'函数运行良好。
所以这是我在这行中的错误:“ free((* list)-> storage [a])”
此分配是错误的:
listptr->storage = (char**)malloc(size * sizeof(char));
^^^^^
由于storage
是char**
因此sizeof应该为sizeof(char*)
。 当您仅使用sizeof(char)
,最终会占用很少的内存,后来又在分配的内存之外进行写操作。
也是这一行:
list->storage[pos] = string;
似乎错了。
在这里您可能需要像这样的strcpy
:
strcpy(list->storage[pos], string)
并在字符串分配的malloc中添加1,即
malloc((1 + strlen(string)) * sizeof(char));
但请注意, sizeof(char)
始终为1,因此
malloc(1 + strlen(string));
很好
顺便说一句:正确设置malloc的一个好方法是使用“ sizeof what_the_variable_points_to”。 喜欢:
char** x = malloc(size * sizeof *x);
^^
Use *x instead of sizeof(char*)
这样,您始终可以获得正确的尺寸,并避免了由于简单的错字造成的错误。
以您的代码为例:
List* listptr = malloc(sizeof(List)); // works but
List* listptr = malloc(sizeof *listptr); // this is less error prone
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.