c中for循环的分段错误

时间:2012-11-21 01:30:23

标签: c

我正在写一个磁力计采样功能。

它按预期进行循环,其中samplesPerAxis = 33且MAX_AXES为3且MAX为999

正如您所见,for循环完成后会发生分段错误,但最终的“结束”不会打印。

void createSamplingData(){
    int i, indexOfValue,  numaxis=0, sampling_value ;
    printf("%i %i %i\n", magmin[0], magmin[1], magmin[2]);
    printf("%i %i %i\n", magmax[0], magmax[1], magmax[2]);

    for (numaxis = 0; numaxis < MAX_AXES; numaxis++){
        printf("beginAxis: %i\n", numaxis);

        sampling_value = magmin[numaxis];
        for (i = samplesPerAxis*numaxis ; i < samplesPerAxis*(numaxis+1) ; i++){
            indexOfValue = findIndexOfClosestValue(sampling_value, numaxis);
            printf("%i: %i => %i\t", i, sampling_value, indexOfValue);
            MagSamples[i][0] = MagInput[indexOfValue][0];
            MagSamples[i][1] = MagInput[indexOfValue][1];
            MagSamples[i][2] = MagInput[indexOfValue][2];            
            printf("%i %i %i\n", MagSamples[i][0], MagSamples[i][1], MagSamples[i][2]);
            sampling_value = sampling_value + (magmax[numaxis]-magmin[numaxis])/samplesPerAxis;
        // creates and even range between mag in min in each axis
        }
        printf("end axis\n");
    }
    printf("\nend");
}

输出我得到:...

beginAxis: 0
0: 32648 => 263         32648 32760 32916
1: 32656 => 258         32656 32724 32888
2: 32664 => 130         32664 32754 32898
...
29: 32880 => 488    32880 32774 32804
30: 32888 => 469    32888 32706 32822
31: 32896 => 990    32896 32752 32812
32: 32904 => 973    32904 32808 32844
end axis
beginAxis: 1
33: 32624 => 463    32790 32624 32906
34: 32631 => 685    32784 32632 32884
35: 32638 => 652    32756 32638 32926
36: 32645 => 465    32833 32645 32867
...
63: 32834 => 601    32690 32834 32930
64: 32841 => 597    32689 32841 32923
65: 32848 => 627    32690 32848 32914
end axis
beginAxis: 2
66: 32769 => 511    32793 32749 32769
67: 32777 => 512    32785 32755 32777
68: 32785 => 520    32769 32731 32785
69: 32793 => 504    32853 32707 32793
...
98: 33025 => 86 32805 32775 33025
end axis

Segmentation fault: 11

发生了什么事?

编辑: samplesPerAxis定义为

#define samplesPerAxis 33

1 个答案:

答案 0 :(得分:2)

作为猜测,我会说故障超出了功能范围。该功能以打印结束

 printf("\nend");

请注意,没有尾随'\ n',因此直到稍后才会刷新“end”。因此,您不会在输出中看到它。与此同时,你继续并遇到错误。

编辑:

i think you are right. Could you elaborate on how the flush would 
process with the trailing \n?

printf函数会缓存您发送到stdout的内容,并在遇到换行符'\ n'时将其刷新(即将其发送到终端)(在您提供的内容中)。要强制它在不添加换行符的情况下进行刷新,可以使用fflush(stdout);