我正在构建一个有限元求解器。以下是我的结构。
// Describes the cartesian grid used in the problem
typedef struct
{
int N; // Number of segments along each direction
double lb_x;
double ub_x;
double lb_y;
double ub_y;
double h; // Max grid resolution
double* grid_nodes_x; // Partition in x direction
double* grid_nodes_y; // Partition in y direction
} grid;
// subdomain object is defined before this
// Domain object
typedef struct domain
{
grid* cartesian_grid; // Reference to the grid object
vertex* vertices; // Array of all vertexes in the domain
int subdomain_count_x; // Subdomains in X direction
subdomain* subdomains; // List of all subdomains
int** subdomain_vertex_map; // Map of subdomain to vertices, gives the local vertex order for assembly
} domain;
现在,我正在尝试为域内的int** subdomain_vertex_map
字段分配空间,如下所示:
// Create one big domain
domain* build_cartesian_domain(grid* cartesian_grid, int subdomain_count_x)
{
int i,j;
domain* cartesian_domain;
#define CGN (cartesian_grid->N + 1)
cartesian_domain = (domain*) calloc(1, sizeof(cartesian_domain));
cartesian_domain->cartesian_grid = cartesian_grid;
cartesian_domain->subdomain_count_x = subdomain_count_x;
cartesian_domain->subdomain_vertex_map = (int**) calloc(2, sizeof(int*));
#define CDM (cartesian_domain->subdomain_vertex_map)
for(i = 0; i < 2; i++)
{
cartesian_domain->subdomain_vertex_map[i] = (int*) calloc(10, sizeof(int));
for(j = 0; j < CGN*CGN; j++)
{
CDM[i][j] = -1;
}
}
#undef CGN
#undef CDM
return cartesian_domain;
}
目前,有些尺寸是硬编码的,用于说明问题。我遇到的问题是内存没有被分配或被分配但是没有存储在双指针数组cartesian_domain->subdomain_vertex_map
中,如下面的gdb跟踪所示:
Breakpoint 1, build_cartesian_domain (cartesian_grid=0x606010, subdomain_count_x=1) at domain.c:16
16 cartesian_domain = (domain*) calloc(1, sizeof(cartesian_domain));
(gdb) n
17 cartesian_domain->cartesian_grid = cartesian_grid;
(gdb)
18 cartesian_domain->subdomain_count_x = subdomain_count_x;
(gdb)
19 cartesian_domain->subdomain_vertex_map = (int**) calloc(2, sizeof(int*));
(gdb)
21 for(i = 0; i < 2; i++)
(gdb)
23 cartesian_domain->subdomain_vertex_map[i] = (int*) calloc(10, sizeof(int));
(gdb)
24 for(j = 0; j < CGN*CGN; j++)
(gdb) p cartesian_domain->subdomain_vertex_map
$1 = (int **) 0x606700
(gdb) p cartesian_domain->subdomain_vertex_map[i]
$2 = (int *) 0x0
(gdb) p i
$3 = 0
(gdb)
有关如何调试此问题的任何想法?谢谢!
答案 0 :(得分:4)
取消引用指针以获取cartesian_domain
的大小(并且不要施放calloc
)
cartesian_domain = (domain*) calloc(1, sizeof(cartesian_domain));
应该是
cartesian_domain = calloc(1, sizeof(*cartesian_domain));
或
cartesian_domain = calloc(1, sizeof(domain));
如何调试未分配内存的原因或结果 分配不存储?
分配但尺寸错误,请查看valgrind