如何解决malloc初始化二维数组上的分割错误
我的程序由于分段错误而失败。使用gdb,我可能会发现问题出在我在函数中初始化2d数组时。
我的编译器标志为-Wall -Wpedantic -Wextra -Wconversion -std=gnu11
这是我正在使用的功能。错误出现在第4行。我不明白为什么会在这里中断,对C来说我是个初学者。
1 char ** get_categories_names(char * file_route,unsigned int maximum_categories) {
2 unsigned int category_counter = 0;
3
4 char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
5 char * category = "";
6 FILE * categories_config;
7 categories_config = fopen(file_route,"r");
8
9 if (categories_config == NULL)
10 {
11 perror("Error while opening the file.\n");
12 exit(EXIT_FAILURE);
13 }
14
15 while (fgets(category,255,categories_config) && category_counter < maximum_categories) {
16 printf("%d",category_counter);
17 categories_list[category_counter] = malloc(100 * sizeof(char));
18 category[strcspn(category,"\n")] = 0;
19 categories_list[category_counter] = category;
20 category_counter++;
21 }
22 fclose(categories_config);
23 return categories_list;
这是gdb结果:
(gdb) step
11 char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) step
__GI___libc_malloc (bytes=40) at malloc.c:3028
3028 malloc.c: No existe el archivo o el directorio.
这是我正在阅读的文本文件:
horror
mystery
FPS
memes
comedy
解决方法
有很多问题。然后,我将尝试在您的代码中修复问题,并添加有关原因的注释。请注意,我没有编译,所以可能会有一些错字
Logging.cs
此外,LogManager
可能返回char ** get_categories_names(char * file_route,unsigned int maximum_categories) {
unsigned int category_counter = 0;
// don't cast the result of malloc
char ** categories_list = malloc(maximum_categories * sizeof(char *));
// declare category as array to provide memory for fgets()
char category[255];
FILE * categories_config;
categories_config = fopen(file_route,"r");
if (categories_config == NULL)
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
// use sizeof array so you don't have to repeat array size
while (fgets(category,sizeof category,categories_config) && category_counter < maximum_categories) {
printf("%d",category_counter);
category[strcspn(category,"\n")] = 0;
// alloc the right size -- sizeof( char ) is always 1 and can be omitted
categories_list[category_counter] = malloc(strlen(category)+1);
// copy strings w/ strcpy()
strcpy(categories_list[category_counter],category);
// the two commands above could be replaced by
//categories_list[category_counter] = strdup(category);
category_counter++;
}
fclose(categories_config);
return categories_list;
。那也应该检查
关于;
rcmdcheck::rcmdcheck()
这并不是说发生段故障事件。
相反,这意味着您没有(gdb) step
11 char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) step
__GI___libc_malloc (bytes=40) at malloc.c:3028
3028 malloc.c: No existe el archivo o el directorio.
可见的'malloc.c'源代码
为避免此类问题,建议:
gdb
将执行对(gdb) step
11 char ** categories_list = (char **)malloc(maximum_categories * sizeof(char *));
(gdb) next
的调用,但直到代码中的下一条语句才会停止
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。