在回答另一个问题时,我写了一些简单的代码来初始化和打印2D数组.但是一些非常奇怪的事情正在发生.
#include <stdio.h>
#include <stdlib.h>
void print_row( const int *row, size_t num_cols ) {
printf("%p\n", (void*)row);
for( size_t col_num = 0; col_num < num_cols; col_num++ ) {
printf(" %2d ", row[col_num]);
}
puts("");
}
int **make_board( const size_t num_rows, const size_t num_cols ) {
int **board = malloc( sizeof(int) * num_rows );
for( size_t row_num = 0; row_num < num_rows; row_num++ ) {
int *row = calloc( num_cols, sizeof(int) );
board[row_num] = row;
print_row(row, num_cols);
}
return board;
}
void print_board( int **board, const size_t num_rows, const size_t num_cols ) {
for( size_t row_num = 0; row_num < num_rows; row_num++ ) {
const int *row = board[row_num];
print_row(row, num_cols);
}
}
int main() {
size_t num_rows = 6;
size_t num_cols = 4;
puts("Making the board");
int **board = make_board(num_rows, num_cols);
puts("Printing the board");
print_board(board, num_rows, num_cols);
}
Run Code Online (Sandbox Code Playgroud)
运行它,我偶尔会得到一个损坏的行,但只有永远print_board不会make_board.
cc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c99 -pedantic -g -c -o test.o test.c
cc test.o -o test
Making the board
0x7fc4e6d00370
0 0 0 0
0x7fc4e6d001e0
0 0 0 0
0x7fc4e6d001f0
0 0 0 0
0x7fc4e6d00200
0 0 0 0
0x7fc4e6d00210
0 0 0 0
0x7fc4e6d00220
0 0 0 0
Printing the board
0x7fc4e6d00370
0 0 0 0
0x7fc4e6d001e0
-422575600 32708 -422575584 32708
0x7fc4e6d001f0
0 0 0 0
0x7fc4e6d00200
0 0 0 0
0x7fc4e6d00210
0 0 0 0
0x7fc4e6d00220
0 0 0 0
Run Code Online (Sandbox Code Playgroud)
如果我在包中链接,比如glib-2,则更频繁地发生损坏.
cc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c99 -pedantic -g `pkg-config --cflags glib-2.0` -c -o test.o test.c
cc `pkg-config --libs glib-2.0` test.o -o test
Run Code Online (Sandbox Code Playgroud)
内存位置都是正确的.初始化期间所有行都很好.没有编译器警告.-fsanitize=address发现没有错误.
可能导致一行损坏的原因是什么?有人甚至可以重复这个问题吗?
$ cc --version
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin17.6.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
$ uname -a
Darwin Windhund.local 17.6.0 Darwin Kernel Version 17.6.0: Tue May 8 15:22:16 PDT 2018; root:xnu-4570.61.1~1/RELEASE_X86_64 x86_64 i386 MacBookPro8,1 Darwin
Run Code Online (Sandbox Code Playgroud)
您将int指针数组分配为int数组,从而导致一些意外行为.简单的修复,幸运的是.
替换此行:
int **board = malloc( sizeof(int) * num_rows );
Run Code Online (Sandbox Code Playgroud)
有了这条线:
int **board = malloc( sizeof(int *) * num_rows );
Run Code Online (Sandbox Code Playgroud)
或者,为了避免将来出现这种错误,正如Jonathan Leffler在评论中所指出的那样,您可以sizeof在您尝试分配的解引用变量上执行运算符,这样您就不必担心类型是否正确:
int **board = malloc( sizeof(*board) * num_rows );
Run Code Online (Sandbox Code Playgroud)