将动态结构传递给函数时出现分段错误(核心已转储)
Segmentation Fault (core dumped) When Passing Dynamic Struct to Function
我正在努力让它为我的作业工作,但我一直收到分段错误,但我看不出有什么问题。
struct line{
int source;
int dest;
int type;
int port;
char data[51];
};
int main(){
struct line *dataIn;
dataIn = malloc(sizeof(struct line));
int nRecords = 0;
readFile(&nRecords, dataIn);
int i=0;
for(i = 0; 1 < 100; i++){
printf("Source: %d Data: %s\n", dataIn[i].source, dataIn[i].data);
}
return 0;
}
void readFile(int *nRecords, struct line *dataIn){
FILE *fileIn;
fileIn =fopen("data.txt","r");
if (!fileIn){
puts("File Open Error");
return 1;
}
while(fscanf(fileIn, "%d:%d:%d:%d:%[^\n]", &dataIn[*nRecords].source, &dataIn[*nRecords].dest, &dataIn[*nRecords].type, &dataIn[*nRecords].port, dataIn[*nRecords].data) == 5){
nRecords++;
dataIn = realloc(dataIn,(*nRecords+1)*sizeof(struct line));
}
fclose(fileIn);
}
另外当我在顶部添加函数原型时:
void readFile(int*, struct line*);
我收到错误:
Conflicting Types for 'readFile'
C 在函数参数传递中使用按值传递。在您的代码中,dataIn
本身使用按值传递传递给 readFile()
。
现在,dataIn
本身就是一个指针,你可以从函数中改变dataIn
的内容,但是你不能改变dataIn
本身(看realloc()
) 从函数中,并期望它被反射回 main()
.
因此,返回后,您的 dataIn
只有一个元素,就像之前 malloc()
ed 一样。然后,for 循环显然会尝试访问超出限制的内存,从而创建 undefined behavior.
如果要从函数中更改dataIn
,需要将指向它的指针传递给函数。
也就是说,
nRecords
是一个指针,nRecords++;
将不会更新相应的int
值。
void
函数 readFile()
不应有 return
语句,其值如 return 1;
我正在努力让它为我的作业工作,但我一直收到分段错误,但我看不出有什么问题。
struct line{
int source;
int dest;
int type;
int port;
char data[51];
};
int main(){
struct line *dataIn;
dataIn = malloc(sizeof(struct line));
int nRecords = 0;
readFile(&nRecords, dataIn);
int i=0;
for(i = 0; 1 < 100; i++){
printf("Source: %d Data: %s\n", dataIn[i].source, dataIn[i].data);
}
return 0;
}
void readFile(int *nRecords, struct line *dataIn){
FILE *fileIn;
fileIn =fopen("data.txt","r");
if (!fileIn){
puts("File Open Error");
return 1;
}
while(fscanf(fileIn, "%d:%d:%d:%d:%[^\n]", &dataIn[*nRecords].source, &dataIn[*nRecords].dest, &dataIn[*nRecords].type, &dataIn[*nRecords].port, dataIn[*nRecords].data) == 5){
nRecords++;
dataIn = realloc(dataIn,(*nRecords+1)*sizeof(struct line));
}
fclose(fileIn);
}
另外当我在顶部添加函数原型时:
void readFile(int*, struct line*);
我收到错误:
Conflicting Types for 'readFile'
C 在函数参数传递中使用按值传递。在您的代码中,dataIn
本身使用按值传递传递给 readFile()
。
现在,dataIn
本身就是一个指针,你可以从函数中改变dataIn
的内容,但是你不能改变dataIn
本身(看realloc()
) 从函数中,并期望它被反射回 main()
.
因此,返回后,您的 dataIn
只有一个元素,就像之前 malloc()
ed 一样。然后,for 循环显然会尝试访问超出限制的内存,从而创建 undefined behavior.
如果要从函数中更改dataIn
,需要将指向它的指针传递给函数。
也就是说,
nRecords
是一个指针,nRecords++;
将不会更新相应的int
值。void
函数readFile()
不应有return
语句,其值如return 1;