C语言 在malloc()之后访问数组时突然出现分段错误



我有一个数组char *Input[11]。我使用malloc()为它分配内存。

    for(int i = 0; i < 12; i++) 
        Input[i] = "";
    for(int i = 0; i < 12; i++)
    {
        Input[i] = malloc( 256 * sizeof(char) );
    }
    for(int i = 0; i < 12; i++)
    {
        strcpy(Input[i], "test");
    }
    printf("Input[11] is %sn", Input[11]); // <- Here the seg fault happens

当我想访问Input[11]之后,我得到一个分割故障。我读到,当没有Input[11]指向的地方时,你通常会在上下文中得到这个错误,所以我猜我如何分配内存有问题。访问Input[10]及以下工作正常。我用valgrind检查了一下,这是错误信息:

==5633== 1 errors in context 1 of 1:
==5633== Invalid read of size 1
==5633==    at 0x4098383: vfprintf (vfprintf.c:1632)
==5633==    by 0x409D695: printf (printf.c:33)
==5633==    by 0x8048A15: handle_command (swebsh.c:122)
==5633==    by 0x8048BE6: main (swebsh.c:181)
==5633==  Address 0x6e69622f is not stack'd, malloc'd or (recently) free'd

然而,我真的不确定这告诉我什么,除了错误在哪里。如有任何帮助,不胜感激。

编辑:哎呀,在简化代码时忘记了初始化!

如果一个数组有N个元素,那么有效的索引范围是[0, N-1]在你的代码片段中,你声明了一个数组有11个元素。因此,数组的有效索引范围是[0, 10]

为了避免类似的错误,不要使用幻数。

你的代码可以这样重写

#define N 11
//...
char *Input[N] = { 0 };
int length = 256;
for( int i = 0; i < N; i++ )
{
    Input[i] = malloc( length * sizeof( char ) );
}
for ( int i = 0; i < N; i++ ) strcpy( Input[i], "test" );
printf( "Input[N - 1] is %sn", Input[N - 1] );

最新更新