gpt4 book ai didi

c - C 中的段错误(代码转储)错误

转载 作者:行者123 更新时间:2023-11-30 19:17:02 24 4
gpt4 key购买 nike

我试图运行此代码,它显示“段错误(代码已转储)”,我如何修复我的代码以使此错误消失。这是我的代码,所以如果有人可以帮助我,那就太棒了!我该如何修复无效的搜索

#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);
}

最佳答案

这段代码中有太多错误,但这是最明显的:

    char* token = strtok(line, " ");
struct _data* temp = (struct _data*)malloc(sizeof(struct _data)*1000);
temp->name = token;

您将 temp->name 设置为 token 的值。但是 token 指向 line,它正在被修改,并且很快就会不复存在,因为您在即将消失的堆栈上创建了它。

您无法保存指向要重用的内存块的指针。

关于c - C 中的段错误(代码转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28820594/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com