指针奇怪的行为

时间:2011-02-21 09:07:36

标签: c pointers

尝试运行这段代码:

void print_matrix(matrix* arg)
{
     int i, j;
     for(i = 0; i < arg->rows; i++) {
         for(j = 0; j < arg->columns; j++) {          // gdb shows, that arg->columns value
             printf("\n %f", arg->data[i][j]);        // has been changed in this line (was 
         }                                            // 3, is 0)
         printf("\n");
     }
}

matrix是一个结构:

typedef struct matrix_t 
{
    int rows;
    int columns;
    double** data;

} matrix;

arg被正确分配3x3矩阵,行= 3,列= 3

功能仅打印\ n's。

编译器是gcc 4.5。 有什么想法吗?

编辑:

int main()
{
    matrix arg;
    arg.rows = 3;
    arg.columns = 3;
    arg.data = (double**)malloc(sizeof(double*) * arg.rows);
    int i;
    for(i = 0; i < arg.rows; i++) {
       arg.data[i] = (double*)malloc(sizeof(double) * arg.columns);
    }

    arg.data[0][0] = 1; 
    arg.data[0][1] = 2;
    //......
    print_matrix(&arg);


    for(i = 0; i < arg.rows; i++) {
        free(arg.data[i]);
    }
    free(arg.data);

    return EXIT_SUCCESS;
}

2 个答案:

答案 0 :(得分:2)

如上面的评论所述,代码似乎没有任何问题。在我的机器和IDEone上编译时工作正常。见http://ideone.com/SoyQH

我有几分钟的时间,所以我跑了几个额外的检查。这几乎是我在每次代码提交之前或在调试时需要一些提示时所采取的步骤。

使用严格的编译器标志进行测试

使用-Wall -pedantic使用gcc进行编译时,有一些关于ISO C90不兼容性的警告,但没有显示停止者。

[me@home]$ gcc -Wall -pedantic -g k.c
k.c:17:55: warning: C++ style comments are not allowed in ISO C90
k.c:17:55: warning: (this will be reported only once per input file)
k.c: In function `main':
k.c:30: warning: ISO C90 forbids mixed declarations and code

与以下相关的警告:

  • 使用C ++样式注释,即//而不是/* ... */
  • main()中,int i;的声明与代码混在一起。 C90希望所有声明都在开始时完成。

使用拆分

解决上述警告后,在代码上运行splint -weak

[me@home]$ splint -weak k.c
Splint 3.1.1 --- 15 Jun 2004

Finished checking --- no warnings

无需报告。

Valgrind的

Valgrind确认没有内存泄漏但是抱怨在printf中使用了unitialised值(并非args->data中的所有元素都被赋予了值)。

[me@home]$ valgrind ./a.out
==5148== Memcheck, a memory error detector.
... <snip> ...
==5148==

 1.000000
 2.000000
==5148== Conditional jump or move depends on uninitialised value(s)
==5148==    at 0x63D6EC: __printf_fp (in /lib/tls/libc-2.3.4.so)
==5148==    by 0x63A6C4: vfprintf (in /lib/tls/libc-2.3.4.so)
==5148==    by 0x641DBF: printf (in /lib/tls/libc-2.3.4.so)
==5148==    by 0x804842A: print_matrix (k.c:18)
==5148==    by 0x8048562: main (k.c:42)
... <snip> ...
==5148==
==5148== ERROR SUMMARY: 135 errors from 15 contexts (suppressed: 12 from 1)
==5148== malloc/free: in use at exit: 0 bytes in 0 blocks.
==5148== malloc/free: 4 allocs, 4 frees, 84 bytes allocated.
==5148== For counts of detected errors, rerun with: -v
==5148== All heap blocks were freed -- no leaks are possible.

结论

无需报告。继续前进。

答案 1 :(得分:1)

matrix.data是一个狂野的指针。您需要为矩阵分配内存并使data指向它。