在 C 中使用 Malloc 来正确分配 2D 数组



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

第一行 -> ("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)

您看到对非初始化值的访问及其用法

相关内容

  • 没有找到相关文章