【发布时间】:2015-03-02 22:24:38
【问题描述】:
我试图运行这段代码,它说“分段错误(代码转储)”我如何修复我的代码以使这个错误消失。这是我的代码,所以如果有人可以帮助我,那就太棒了!如何修复我的无效搜索
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct _data {
char *name;
long number;
};
int SCAN(FILE *(*stream)){
int count = 0;
char line[256];
while (fgets(line, sizeof(line), *stream)) {
count++;
}
return count;
}
struct _data* BlackBoxLOAD(FILE **stream, int size){
struct _data* BlackBox = (struct _data*)malloc(sizeof(struct _data)*size);
int count = 0;
char line[256];
while (fgets(line, sizeof(line), *stream)) {
char* token = strtok(line, " ");
struct _data* temp = (struct _data*)malloc(sizeof(struct _data));
temp->name = token;
token = strtok(NULL, " ");
temp->number = atoi(token);
BlackBox[count] = *temp;
count++;
}
return BlackBox;
}
void SEARCH(struct _data *BlackBox, char *string, int size){
int i = 0;
for (i = 0; i<size; i++){
if (strcmp(BlackBox[i].name, string) == 0)
return i;
}
return -1;
}
void FREE(struct _data *BlackBox, int size){
free(BlackBox);
return;
}
int main(int argc, char **argv) {
int i = 0, size = 0;
FILE *stream = fopen("hw5.data", "r");
int noOfLines = SCAN(&stream);
size = noOfLines;
struct _data *BlackBox = BlackBoxLOAD(&stream, size);
fclose(stream);
for (i = 1; i<argc; i++){
if (argv[i] == "") {
printf("*******************************************");
printf("* You must include a name to search for. *");
printf("*******************************************");
}
int pos = SEARCH(BlackBox, argv[i], size);
if (pos == -1) {
printf("*******************************************");
printf("The name was NOT found.");
printf("*******************************************");
}
else{
printf("*******************************************");
printf("The name was found at the %d entry.", pos);
printf("*******************************************");
}
}
FREE(BlackBox, size);
}
【问题讨论】:
-
您是否尝试将“分段错误”插入您最喜欢的搜索引擎?
-
对于不知道什么是段错误的人来说,这是一些有趣的复杂代码。
-
不是“code dumped”而是“coredumped”,见core(5);所以基本上用
gcc -Wall -Wextra -g编译你的程序然后使用gdb yourprog core
标签: c file terminal segmentation-fault void