使用格式字符串扫描输入时的分段错误

时间:2012-06-20 03:06:50

标签: c segmentation-fault scanf

考虑代码及其结果:

while ((row = mysql_fetch_row (table_info)) != NULL)
{
    answer='\0';
    printf ( "%s: ", row[0] );
    scanf ( "%c", &answer );
    getchar();
    if ( answer == 'y')
    {
        printf ( "*****\n" );
        table_name[index] = malloc ( strlen(row[0]) + 1 );
        printf ( "*****\n" );
        memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
    }
    printf ( "finally inserted: %s \n", table_name[index]);
}

执行结果:

1_time_access: y
*****
*****
finally inserted: 1_time_access 
2_time_access: y
*****
*****
finally inserted: 2_time_access 
39_time_access: y
*****
*****
finally inserted: 39_time_access 

结果说明:row[0]的值为1_time_access2_time_access39_time_access。现在考虑一种更好的方法,即使用格式字符串来转义\n。我运行以下代码,但它给出了segentation错误,我无法理解为什么。 代码:

while ((row = mysql_fetch_row (table_info)) != NULL)
{
    answer='\0';
    printf ( "%s: ", row[0] );
    scanf ( "%[^\n]%*c", &answer );
    if ( answer == 'y')
    {
        printf ( "*****\n" );
        fflush(stdout);
        table_name[index] = malloc ( strlen(row[0]) + 1 );
        printf ( "*****\n" );
        fflush(stdout);
        memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
    }
    printf ( "finally inserted: %s \n", table_name[index]);
    fflush(stdout);
}

结果:

1_time_access: y
*****
./set-env.sh: line 17: 15263 Segmentation fault      (core dumped) ./exec dataset_one

(不要担心set-env.sh,它是运行该程序的脚本。)

我能理解为什么会这样。

1 个答案:

答案 0 :(得分:4)

if ( answer == 'y')
{
    printf ( "*****\n" );
    fflush(stdout);
    table_name[index] = malloc ( strlen(row[0]) + 1 );
    printf ( "*****\n" );
    fflush(stdout);
    memcpy ( &table_name[index], &row[0], strlen(row[0]) + 1 );
}

                                    /*     BAD      */
printf ( "finally inserted: %s \n", table_name[index]);

只有table_name[index]才会分配answer == 'y',但无论如何都会将其发送到printf。我假设这是发生段错误的行。

调试器是你的朋友。它会显示变量的状态。