c-我怎么才能弄清楚为什么函数有分段错误



我在这个程序中使用的其他函数在执行时工作得很好,但这个方法在加载几秒钟后会出现分段故障核心转储。有人能认出这个问题吗?我试着调试并找出为什么只发生在这个函数上,但我似乎不明白为什么。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int flag = 0, var, currFrame = 0, numFault, currRequest,minRequest,maxRequest ,request;
int numPages, numFrames, numRequest, fc =0, go =0, c =0;
void opt();
void runningMessage(int pg, int frame, int msg){
if(msg == 1)
{
printf("Page %d already in Frame %dn",pg, frame);
}
if(msg == 2)
{
printf("Page %d loaded into Frame %dn",pg, frame);
}
if(msg == 3)
{
printf("Page %d unloaded from Frame %dn",pg, frame);
}

int main(int argc, char *argv[])
{
FILE *fp;
fp = fopen(argv[1], "r");
int x =0;
fscanf(fp, "%d %d %d", &numPages, &numFrames, &numRequest);
int pgAccess[numRequest],pgArray[numPages], pgRequest[numRequest];
while(!feof(fp))
{
fscanf(fp, "%d", &pgAccess[x]);
x++;
}
fclose(fp);
printf("Algorithm: %snn", argv[2]);
var = numRequest;
if(strcmp(argv[2] ,"FIFO") == 0)
{
fifo(&pgArray, &pgAccess, numPages, numFrames, numRequest, var);
}
else if(strcmp(argv[2], "LRU") == 0)
{
lru(pgArray, pgAccess, pgRequest, numPages, numFrames, numRequest, var);
}
else if(strcmp(argv[3], "OPT") == 0)
{
opt(pgArray, pgAccess, pgRequest, numPages, numFrames, numRequest);
}

}
void opt(int *pgArray, int *pgAccess, int *pgRequest, int numPages, int numFrames, int numRequest){
int i=0, x=0, y, a;
for(i = 0; i < numFrames; i++)
{
pgRequest[i] = 0;
pgArray[i] = -1;
}
for(i = 0; i < numRequest; i++)
{
flag = 0;
a = pgAccess[i];
for(y = 0; y < numFrames; y++)
{
if(a == pgArray[y])
{
flag = 1;
runningMessage(pgArray[y], y, 1);
break;
}
}
if((flag == 0) && (x < numFrames))
{
fc++;
pgArray[x] = a;
runningMessage(pgArray[x], x, 2);
x++;
}
else if((flag == 0) && (x == numFrames))
{
fc++;
for(go = 0; go < numFrames; go++)
{
pgRequest[go] = 0;
}
for(currRequest = 0; currRequest < numFrames; currRequest++)
{
c = 0;
for(currFrame = i + 1; currFrame < numRequest; currFrame++);
{
if(pgArray[currRequest] == pgAccess[currFrame])
{
if(pgRequest[currRequest] == 0)
{
pgRequest[currRequest] = currFrame;
c = 1;
}
}
}
if(c != 1)
{
pgRequest[currRequest] = numRequest + 1;
}
}
request = 0;
maxRequest = pgRequest[0];
for(go = 0; go < numFrames; go++)
{
if(pgRequest[go] > maxRequest)
{
maxRequest = pgRequest[go];
runningMessage(pgArray[go], go, 3);
request = go;
}
}
pgArray[request] = a;
runningMessage(pgArray[request], request, 2);
}
}
printf(" %d Page Faultsnn", fc);
}
else if(strcmp(argv[2], "LRU") == 0) { /* whatever */ } 
else if(strcmp(argv[3], "OPT") == 0)

这就是为什么如果你通过一个"OPT",你会得到一个segfault。

调试segfault:

  • 通读您的代码(在这种情况下,问题到此结束(
  • 运行valgrind或任何您喜欢的内存检查器
  • 获取核心转储并进行回溯

相关内容

  • 没有找到相关文章

最新更新