动态字符串数组,但检测到堆损坏

问题描述 投票:0回答:1

我尝试创建一个char指针的动态数组,这意味着指针也可以是动态内存,因此在上面的代码中,我尝试为该数组分配一个大小,然后在他的第一个对象中分配一个字符串。但是我在数组指针上收到“检测到堆损坏”错误。

int main(void)
{

    char** pArr = 0;
    char string[] = "hello";

    pArr = (char**)malloc(sizeof(char) * 1); //make it an array with one element
    *pArr = (char*)malloc(sizeof(char) * (strlen(string) + 1)); //make it an array with the size of string
    strcpy(*pArr, string); //copy string to the first element of the array

    printf("%p", pArr); //the pointer where the heap corruption is detected

    free(pArr);

    getchar();
    return 0;
}

我复制了整个主体,所以您知道我没有想到这一点。

c dynamic-memory-allocation pointer-to-pointer arrayofarrays arrayofstring
1个回答
0
投票

您在这里没有分配足够的空间:

© www.soinside.com 2019 - 2024. All rights reserved.