【发布时间】:2019-07-07 08:10:59
【问题描述】:
我很确定*(pointer+1) = pointer[1]。
我的问题是当我运行这段代码时:
if (NULL == (*str_array = (char **)malloc(sizeof(char *)*10))) {
return ERROR;
}
splitter = strtok(str, TOKEN);
while(splitter != NULL){
if (NULL == ((*str_array )[i] =(char *)malloc(sizeof(char)*strlen(str) +1))){
return ERROR;
}
strcpy((*str_array )[i], splitter);
splitter = strtok(NULL,TOKEN);
i++;
}
我得到一个valgrind 输出,表明我没有泄漏或错误要抑制。该程序运行良好。
但是当我将 (*str_array )[i] 替换为 **(str_array + i) 并运行时
valgrind --leak-check=full ./program 我得到以下输出:
==18873== Invalid write of size 8
==18873== at 0x1089B7: split_func (in /home)
==18873== by 0x108B4E: main (in /home)
==18873== Address 0x3100414747504724 is not stack'd, malloc'd or (recently) free'd
==18873==
==18873==
==18873== Process terminating with default action of signal 11 (SIGSEGV)
==18873== General Protection Fault
==18873== at 0x1089B7: split_func (in /home)
==18873== by 0x108B4E: main (in /home)
==18873==
==18873== HEAP SUMMARY:
==18873== in use at exit: 130 bytes in 3 blocks
==18873== total heap usage: 4 allocs, 1 frees, 1,154 bytes allocated
==18873==
==18873== 11 bytes in 1 blocks are definitely lost in loss record 2 of 3
==18873== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18873== by 0x1089B6: split_func (in /home)
==18873== by 0x108B4E: main (in /home)
==18873==
==18873== LEAK SUMMARY:
==18873== definitely lost: 11 bytes in 1 blocks
==18873== indirectly lost: 0 bytes in 0 blocks
==18873== possibly lost: 0 bytes in 0 blocks
==18873== still reachable: 119 bytes in 2 blocks
==18873== suppressed: 0 bytes in 0 blocks
==18873== Reachable blocks (those to which a pointer was found) are not shown.
==18873== To see them, rerun with: --leak-check=full --show-leak-kinds=all
==18873==
==18873== For counts of detected and suppressed errors, rerun with: -v
==18873== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
Segmentation fault (core dumped)
大家都知道,“str”是一个要在每个“,”(TOKEN)中拆分的字符串,并且“拆分”了char指针来做到这一点。 “str_array”是一个作为参数接收的char ***指针,它应该是一个动态字符串的动态数组。 两次运行之间的唯一区别是我在前面提到的代码中所做的一项更改。谁能告诉我这里发生了什么?
【问题讨论】:
-
请重新考虑您的标签...您是在编码 c 还是 c++?这是一个重要的区别
-
(*str_array)[i]等于*(*str_array + i) -
free丢失。
标签: c pointers memory-leaks segmentation-fault