我有下面的最小示例,其中我的主函数调用两个不同的函数function1()
和function2()
。他们都希望处理一个表,该表需要在function1()
的第一次运行中生成。在我的实际程序中,表要大得多,这就是为什么我不希望它作为全局变量硬编码在程序内存中,而是在第一轮代码中计算。我声明了这个表是静态的,这样当函数离开时,它会保持赋值。我不确定tblPtr
是否也需要是static
。为什么我要在这里获得SEGFAULT?
#include <stdio.h>
static void genTbl(unsigned int encodeTbl[][2])
{
int nn,mm;
for (nn=0; nn < 3;nn++){
for (mm=0; mm < 2; mm++){
encodeTbl[nn][mm] = nn+mm; //some example
}
}
}
unsigned int **tblPtr; //pointer to table
static unsigned int function1()
{
static int t1=0;
static unsigned int tbl[3][2];
if(t1==0){ //only gen table in first round
t1++;
genTbl(tbl);
tblPtr = &tbl; //assign pointer
t1++;
}
return (tbl[2][2]);
}
static unsigned int function2()
{
//also wants to work with tbl
return (tblPtr[2][2]); //SEGFAULT
}
int main()
{
int cnt=0;
while(cnt<5){
int f1 = function1();
printf("function1 return: %dn", f1);
int f2 = function2();
printf("function1 return: %dn", f2);
cnt++;
}
}
在function1()
中,您已经调用了未定义的行为。
您已经定义了类似于static unsigned int tbl[3][2];
的数组,因此有效访问应该是tbl[i][j];
,其中0<i<3
和0<j<2
。因此,在代码中
return (tbl[2][2]);
正在超出限制地使用内存,已超出限制。你在function2()
中也有同样的问题。
也就是说,的声明
tblPtr = &tbl;
无效,并且违反了约束。任何启用了适当警告的conorming编译器都会对该语句发出警告。YOu需要将tblPtr
的类型更改为指向2个int
的数组的指针,类似
unsigned int (*tblPtr)[2];
然后,该分配将保持有效。
将tblPtr声明为用户定义的类型
typedef unsigned int myType[3][2];
myType **tblPtr; //pointer to table
使用此方法,您可以显式地将其声明为指向无符号整数的二维数组的指针。然后将static unsigned int tbl[3][2]
置于功能1 之外