C 指针和数组之间的关系

C 指针和数组之间的关系,c,pointers,memory-leaks,segmentation-fault,C,Pointers,Memory Leaks,Segmentation Fault,我非常确定*(指针+1)=指针[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)*str

我非常确定
*(指针+1)=指针[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_数组+i)
替换
(*str_数组)[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)和“splitter”字符指针中进行拆分。“str_数组”是作为参数接收的字符***指针,它应该是动态字符串的动态数组。 两次运行之间唯一的区别是我在前面提到的代码中所做的一个更改。有人能告诉我这里发生了什么事吗

我非常确定
*(指针+1)
=
指针[1]

对。这两个表达式对于任何数组或指针都是等效的

但是当我用
**(str_数组+i)
替换
(*str_数组)[i]

这两个表达式不相等

(*str_数组)[i]
*(*str_数组)+i)


**(str_数组+i)
*str_数组[i]

请重新考虑您的标签。。。你是在编码C还是C++?这是一个重要的区别,
(*str_数组)[i]
等于
*(*str_数组+i)
缺少免费的