c - C中使用Malloc正确分配二维数组

标签 c memory dynamic segmentation-fault malloc

一个简单的程序必须保存在二维数组中:

第一行 -> ('k','f') 第二行 -> ('c','d')

程序是

#include <stdio.h>
#include <stdlib.h>

int main(){
    char **p;

    p = (char**) malloc (2*sizeof(char*));
    *p = (char*) malloc (2*sizeof(char));

    **p = 'k';
    **(p+1) = 'f';
    *p = *p+1;
    **p = 'c';
    **(p+1) = 'd';
}

程序返回分段核心错误错误。 怎么了?

最佳答案

您的线路有问题

**(p+1) = 'f';

您想要写入*(p+1)中存储的地址(例如p[1]),但您从未初始化p[ 1],并且您写入了无效地址

<小时/>

使用 valgrind 很容易找到此类问题,如果我执行给出的程序:

==3951== Memcheck, a memory error detector
==3951== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3951== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3951== Command: ./a.out
==3951== 
==3951== Use of uninitialised value of size 4
==3951==    at 0x10494: main (c.c:11)
==3951== 
==3951== Invalid write of size 1
==3951==    at 0x10494: main (c.c:11)
==3951==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==3951== 
==3951== 
==3951== Process terminating with default action of signal 11 (SIGSEGV)
==3951==  Access not within mapped region at address 0x0
==3951==    at 0x10494: main (c.c:11)
==3951==  If you believe this happened as a result of a stack
==3951==  overflow in your program's main thread (unlikely but
==3951==  possible), you can try to increase the size of the
==3951==  main thread stack using the --main-stacksize= flag.
==3951==  The main thread stack size used in this run was 8388608.
==3951== 
==3951== HEAP SUMMARY:
==3951==     in use at exit: 10 bytes in 2 blocks
==3951==   total heap usage: 2 allocs, 0 frees, 10 bytes allocated
==3951== 
==3951== LEAK SUMMARY:
==3951==    definitely lost: 0 bytes in 0 blocks
==3951==    indirectly lost: 0 bytes in 0 blocks
==3951==      possibly lost: 0 bytes in 0 blocks
==3951==    still reachable: 10 bytes in 2 blocks
==3951==         suppressed: 0 bytes in 0 blocks
==3951== Rerun with --leak-check=full to see details of leaked memory
==3951== 
==3951== For counts of detected and suppressed errors, rerun with: -v
==3951== Use --track-origins=yes to see where uninitialised values come from
==3951== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 6 from 3)

您可以在其中看到对未初始化值的访问及其使用

关于c - C中使用Malloc正确分配二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54168278/

相关文章:

c - 扫描并打印列表中的全名(C语言)

C中的纸牌游戏,随机播放链表

c - 如何在c中创建动态大小的数组?

c++ - 有效地使用多个分配器

algorithm - 与迷宫相关的游戏

javascript - 当内容溢出超过div的固定高度时如何创建新的div?

C - 重新分配无效的下一个大小的字符串

c - 如何使用C语言加密和解密文本?

c++ - 为什么memcpy复制Eigen矩阵数据失败,std::copy成功?

java - 最小化 Tomcat "per connection"内存占用