C malloc(分段错误:11)

C malloc (Segmentation fault: 11)

我试图理解 malloc,但我一直在使用这段代码 "Segmentation fault: 11":

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

int main()
{
    int i = 0, j = 0;
    char ** ptr = (char **) malloc(sizeof(char*));

    for(i = 0; i < 5; i++)
    {
        for(j = 0; j < 10; j++)
            ptr[i][j] = 'a';

        printf("%s\n", ptr[i]);
    }

    return 0;
}

我以为没有分配足够的字节,所以我做了 malloc(sizeof(char*) * 100,但给了我同样的错误。我在这里有什么不明白的?

分配二维数组时,还需要分配各个子数组。此外,您需要说出您希望拥有多少个元素。为此,您将所需的计数乘以元素的数量,如下所示:

char ** ptr = (char **) malloc(5*sizeof(char*));
// Size=5 ---------------------^
for(int i = 0; i < 5; i++) {
    ptr[i] = malloc(11*sizeof(char));
    // sizeof(char) is always 1, so the multiplication above is redundant.
    // You need 11 elements for ten characters
    for(int j = 0; j < 10; j++) {
        ptr[i][j] = 'a';
    }
    // don't forget to null-terminate the string:
    ptr[i][10] = '[=10=]';
    printf("%s\n", ptr[i]);
}

你的代码在各个方面都一团糟!

1) 您恰好为指向它的 1 个指针分配了内存。这意味着您可以访问 ptr[0],但不能访问 ptr[1] ... ptr[4]。

2) 你永远不会为 ptr[i] 中的元素分配任何东西。

3) 你尝试打印一个字符串 a ptr[i] ,它(即使你的分配是正确的)永远不会终止。

4)虽然这显然只是一个初学者测试,但不要忘记释放你的记忆!!!!

要达到与您的示例代码所描述的内容接近的程度,您可以这样做:

int main() 
{
int i,j;
char ** ptr = malloc( 5 * sizeof(char*) ); /* an array of 5 elements of type char* */
for(i = 0; i < 5; i++)
{
    ptr[i] =  malloc( 11*sizeof(char) ); /* The element i of the array is an array of 11 chars (10 for the 'a' character, one for the null-termination */
    for(j = 0; j < 10; j++)
        ptr[i][j] = 'a';
    ptr[i][10] = '[=10=]'; /* strings need to be null terminated */

    printf("%s\n", ptr[i]);
}
// free your memory!
for (i=0; i<5; i++ )
{
    free(ptr[i]);
}
free(ptr);

return 0;

另一种分配内存的方法是:

char (*ptr)[11] = malloc( sizeof(char[5][11]) );

for(i = 0; i < 5; i++)
{
    for(j = 0; j < 10; j++)
        ptr[i][j] = 'a';

    ptr[i][10] = 0;
    printf("%s\n", ptr[i]);
}

free(ptr);

使用单个分配似乎比使用大量分配更麻烦,除非您有紧迫的理由使用后者。