我很确定 *(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"是每个","(令牌)"one_answers"分离器"的字符串。" str_array"是一个char ***指针,被接收为参数,它应该是动态的动态字符串。两次运行的唯一区别是我在前面提到的代码中所做的一个更改。有人可以告诉我这里发生了什么吗?
我很确定
*(pointer+1)
=pointer[1]
。
是。这两个表达式对于任何数组或指针都是等效的。
但是,当我替换
(*str_array )[i]
时**(str_array + i)
...
这两个表达式不是等效的。
(*str_array )[i]
是*(*str_array ) + i)
**(str_array + i)
是*str_array[i]