gpt4 book ai didi

c - 不知道为什么我用 strtok/EOF 得到 "Bus error 10"

转载 作者:行者123 更新时间:2023-11-30 18:41:08 24 4
gpt4 key购买 nike

我正在尝试读取 txt 文档中的每一行并将每一行标记为特定数据。但是,我在循环结束时不断收到此错误“总线错误 10”。我不确定为什么会发生这种情况,因为缓冲区 char * 有足够的分配内存。

void* Producer(void *arg)
{
printf("\nEntered Producer\n");
int i, item, index;

index = (int)arg;

FILE *f = fopen(bookorders, "r");
char c = fgetc(f);
int z =0;
while (c!=EOF) {
char * buffer = (char *)calloc(1000, 1);
while (c!='\n') {
*(buffer+z) = c;
z++;
c = fgetc(f);
}
char * rpr;

char delim[2] = "|";

char * title = strtok_r(buffer, delim, &rpr);
title = title +1;
int leng = (int)strlen(title);
*(title+leng-1) = '\0';

double cost = atof(strtok_r(NULL, delim, &rpr));

int id = atoi(strtok_r(NULL, delim, &rpr));

char * cat_name = strtok_r(NULL, delim, &rpr);

c = fgetc(f);
printf("%c\n", c);
z = 0;
*buffer = '\0';

free(buffer);
}

fclose(f);
return NULL;
}

我省略了关于互斥体的代码,因为这个框架一开始就不起作用;我想只添加相关代码。另外这个错误与 while 循环的 EOF 条件有什么关系吗?

最佳答案

代码中有大量内容可能会超出缓冲区末尾或取消引用空指针(这可能会导致总线错误)。对我来说重写你的代码比列出所有错误要短,所以这里是:

char *buffer = malloc(1000);
if ( !buffer )
return NULL;

FILE *f = fopen(bookorders, "r");
int c, z;

if ( f ) for (;;)
{
for ( z = 0; z < 999 && (c = fgetc(f)) != EOF && c != '\n'; ++z )
buffer[z] = c;

if ( z == 0 && c == EOF )
break;

buffer[z] = 0;

char const delim[] = "|";
char *rpr;
char *title = strtok_r(buffer, delim, &rpr);
if ( title[0] )
{
++title;
title[strlen(title) - 1] = 0;
}

// Would be better to use `strtod` and `strtol` here
char *ptr = strtok_r(NULL, delim, &rpr);
double cost = ptr ? atof(ptr) : 0;

ptr = strtok_r(NULL, delim, &rpr);
int id = ptr ? atoi(ptr) : 0;

char * cat_name = strtok_r(NULL, delim, &rpr);

// If you want to do something with title, cost, id, cat_name, now's the chance
}

free(buffer);
fclose(f);
return NULL;

关于c - 不知道为什么我用 strtok/EOF 得到 "Bus error 10",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23001466/

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