【发布时间】:2015-04-16 22:55:37
【问题描述】:
我正在尝试在 linux ubuntu 中运行此 C 编程。我遇到了错误分段错误(核心转储)。我正在尝试读取包含以下格式的行的文本文件:
key01 value01
key02 value02
key03 value03
这是我的程序。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ARY 50
int main()
{
int i=0;
int numProgs=0;
char* lines[MAX_ARY];
char line[40];
int j;
char search_key[1000];
int position=6, length=5, c = 0;
char str[10];
int ret=0;
char* token;
char* my_key;
FILE *file;
file = fopen("client1.txt", "r");
while(fgets(line, sizeof line, file)!=NULL)
{
//check to be sure reading correctly
//printf("%s", line);
//add each filename into array of programs
lines[i]=malloc(sizeof(line));
strcpy(lines[i],line);
i++;
//count number of programs in file
numProgs++;
}
//check to be sure going into array correctly
for (j=0 ;j<numProgs+1;j++)
{
//printf("%s", lines[j])
;
}
printf("Please enter your search:");
scanf("%s",str);
for(i = 0; i<numProgs; i++)
{
// Gettng the univ names from the list
token = strtok(lines[i]," ");
/* walk through other tokens */
while( token != NULL )
{
ret=strcmp(str, token);
printf("str=%s\t token=%s ret=%d\n", str, token, ret);
token = strtok(NULL," ");
if(ret==0)
{
//now token should be my required token, so break here
break;
}
}
if (ret == 0)
break;
}
printf("Required substring is: %s\n", token);
//send(token,to-server1);
fclose(file);
return 0;
}
我无法修复错误。
【问题讨论】:
-
您的代码可能有很多可能导致分段错误的原因,它基本上是许多地方的缓冲区溢出的可能性,最值得注意的是
scanf("%s", str);,因为sizeof(str) == 10,还有malloc(sizeof(line))可能是malloc(strlen(line) + 1)而不是,如果您只想复制读取的字节,请更改为scanf("%9", str);并检查问题是否仍然存在。 -
如果您还没有学会使用 gdb,那么现在是开始的好时机。如果您在启用调试符号的情况下进行编译,gdb 可以准确地告诉您发生了段错误,并让您检查相关的变量值以查看问题所在。
-
检查
fopen()的返回码(在你的情况下它是file变量)。fopen()可以在出现错误时返回NULL。尝试进一步使用file变量(实际上是指针)可能会导致段错误(取消引用此指针时)。请记住在继续之前始终检查库函数/系统调用的返回码。 -
显示你的输入和输出。
-
你的文本文件有多少行?
标签: c linux segmentation-fault