gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:03:18 26 4
gpt4 key购买 nike

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

第一行 -> ('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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com