【发布时间】:2011-07-28 02:00:58
【问题描述】:
您好,我正在用 C 编写一个程序,但是在运行我的程序时遇到了分段错误。
我正在使用 gcc 编译,编译时没有任何警告或错误。
我尝试使用 gdb 来跟踪段错误的起源,它会将我引导到我将数据值分配给我的二维数组的行: 数组[行][列] = 数据值;
当我运行我的程序时,会存储 3 个数据值,然后会出现段错误。它应该将数据存储在 424 行 x 117 列上,但在仅存储 3 个数据值后始终会出现分段错误。
我的代码如下(省略了一些细节):
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void allmem(float** fpdata,...); // allocate memory header
void stored(float** fpdata,...); // store data header
void countnumber(int* num1, int*num2,...); // count header
int main() // main() function
{
int numberofrows = 424; // number of rows
float** fpdata; // two dimensional array fpdata of floats
allmem(fpdata,...); // call allocate memory function
stored(fpdata,...); // call function to store data
...
return 0;
} // main ()
// --------------stored() function---------------
void stored(float** fpreal,...) {
FILE *fp; // file pointer
float datavalue; // variable to hold data values read
int row;
int column;
fp = fopen("c:/file.txt","r");
for(column = 0; column < 117; column++) {
for(row = 0; row < 424; row++) {
fscanf(fp, "%f,", &datavalue);
fpdata[row][column] = datavalue;
} // for
} // for
fclose(fp);
} // stored()
// ----------allmem() function----------------
// function to allocate memory for two dimensional arrays
// I have hard coded the values of the array sizes in, but
// in my actual program they are calculated at run time based
// on the size of some input files and this is done in the
// countnumber() function
void allmem(float** fpdata,...) {
int i = 0;
fpdata = (float**) malloc((424)*sizeof(float*));
fpdata2 = (float**) malloc((424)*sizeof(float*));
...
for (i = 0; i<424; i++) {
fpdata[i] = (float*) malloc((117)*sizeof(float));
fpdata2[i] = (float*) malloc((117)*sizeof(float));
} // for
} // allmem()
【问题讨论】:
-
您是否正在检查以确保您对
malloc的所有调用都成功返回? -
你说得对,我很抱歉。我删除了我的答案。
-
是的,我检查了没有返回空指针,我没有内存不足,我想我只是以某种方式写入分配的内存位置,但我不知道如何这发生了。
-
谢谢你的帮助 karlphillip
标签: c memory dynamic segmentation-fault