我的程序在循环迭代过程中遇到了段错误。调用中间函数后,inter_value
打印直到inter_value[199][208]
,然后,我有一个段错误。为了确保它没有超出范围访问,我inter_value
首先打印数组,然后数组打印没有任何问题。
这是内存不足的象征吗?由,创建的数组ct
和是一个静态数组。inter_value
malloc
key_byte
D = 200;
K = 256;
for(j = 0; j < D; j++)
for(i = 0; i < K; i++)
printf("inter_value[%i][%i] = %i\n", j, i, inter_value[j][i]);
for(j = 0; j < D; j++) {
for(i = 0; i < K; i++) {
intermediate(ct[j][0], key_byte[i], &inter_value[j][i]);
printf("inter_value[%i][%i] = %i\n", j, i, inter_value[j][i]);
fflush(stdout);
}
}
printf("rex\n");
for(j = 0; j < D; j++) {
for(i = 0; i < K; i++) {
hamming_dist(ct[j][0], inter_value[j][i], &h[j][i]);
}
}
中间函数在这里
void intermediate(unsigned char ct, unsigned char key_byte, unsigned char *inter_value){
*inter_value = getSBoxInvert(ct^key_byte);
}
编辑 1:数组声明。
//initialize different intermediate values
inter_value = (unsigned char**)malloc(D * sizeof(unsigned char*));
if(inter_value == NULL){
fprintf(stderr, "out of memory\n");
return 0;
}
for(i = 0; i < D; i++){
inter_value[i] = (unsigned char *)malloc(K * sizeof(unsigned char)); // this is fix to key size
if(inter_value[i] == NULL){
fprintf(stderr, "out of memory\n");
return 0;
}
}
//ct = malloc(row * sizeof(unsigned char*));
ct = (unsigned char**)malloc(D * sizeof(unsigned char*));
if(ct == NULL){
fprintf(stderr, "out of memory\n");
return 0;
}
for(i = 0; i < D; i++){
//ct[i] = malloc(column * sizeof(unsigned char));
ct[i] = (unsigned char *)malloc(column * sizeof(unsigned char));
if(ct[i] == NULL){
fprintf(stderr, "out of memory\n");
return 0;
}
}
unsigned char key_byte[256] = {0};
编辑2:段故障前的打印输出。
inter_value[199][233] = 214
inter_value[199][234] = 119
inter_value[199][2
编辑 3:gdb 输出(似乎它指向另一个函数)
程序收到信号 SIGSEGV,分段错误。0x0804a3f5 in hamming_dist (ct=31 '\037', inter_value=203 '\313', h=0x2) at cpa.cpp:53 53 *h = c;
编辑 4:从 gdb 发出回溯命令后...
#0 0x0804a3f5 in hamming_dist (ct=31 '\037', inter_value=203 '\313', h=0x2) at cpa.cpp:53
#1 0x0804aff5 in main (argc=3, argv=0xbffff2f4) at cpa.cpp:266
编辑 5:在其之前添加 hamming_dist 函数调用和 printf 调用。
编辑 6:初始化 h
int **h;
h = (unsigned int**)malloc(D * sizeof(unsigned int*));
if(h == NULL){
fprintf(stderr, "out of memory\n");
return 0;
}
for(i = 0; i < D; i++){
h[i] = (unsigned int*)malloc(K * sizeof(unsigned int)); // this is fix to key size
if(h[i] == NULL){
fprintf(stderr, "out of memory\n");
return 0;
}
}
编辑 7:hamming_dist 函数声明。
void hamming_dist(unsigned char ct, unsigned char inter_value, int *h){
int temp;
temp = ct ^ inter_value;
//then count No. of ones
int c; // c accumulates the total bits set in v
for (c = 0; temp; c++)
temp &= temp - 1; // clear the least significant bit set
*h = c;
}