gpt4 book ai didi

C:strcpy 的段错误

转载 作者:行者123 更新时间:2023-11-30 20:10:40 34 4
gpt4 key购买 nike

我想知道是否有人可以帮助我解决这个段错误,valgrind 和 gdb 指向 strcpy(),但我仍然找不到它..

void listusers(userstat* ptustat)
{
FILE* fileu = openfile("user_db");
char* str = (char*) malloc(sizeof(char)*100);
char* temp = (char*) malloc(sizeof(char)*100);
int i = 0;
int offset = 0;
while (fgets(str,100,fileu) != NULL)
{
strcpy(temp,str);
strcpy((*(ptustat+i)).name,strtok(temp,"#"));
offset+=(strlen(temp)+1);
strcpy(temp,str+offset);
strcpy((*(ptustat+i)).contact,strtok(temp,"#"));
offset+=(strlen(temp)+1);
strcpy(temp,str+offset);
strcpy((*(ptustat+i)).uname,strtok(temp,"#"));
offset+=(strlen(temp)+1);
strcpy(temp,str+offset);
strtok(temp,"#");
offset+=(strlen(temp)+1);
strcpy(temp,str+offset);
(*(ptustat+i)).saldo = atof(strtok(temp,"\n"));
i++;
}
closefile(fileu);
free(str);free(temp);
}

用户统计定义:

typedef struct userstat {
char name[50];
char contact[50];
char uname[50];
float saldo;
} userstat;

它正在读取的文件也有这样的行:姓名#联系人#用户名#密码#钱

gdb 回溯:

    Program received signal SIGSEGV, Segmentation fault.
__strcpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:296
296 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: Ficheiro ou directoria inexistente.
(gdb) bt
#0 __strcpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:296
#1 0x00000000004030b2 in listusers ()
#2 0x0000000000401fee in statsmenu ()
#3 0x0000000000401c1d in menuinit ()
#4 0x0000000000400ecc in main ()
(gdb)

函数的调用和结构体的分配:

void statsmenu()
{

char x = '0';

getchar();
while (1)
{
prodstat db[100] = {{"",0.00,0.00,0.00}};
prodstat *ptstat = db;
userstat dbu[100] = {{"","","",0.00}};
userstat *ptustat = dbu;
listproducts(ptstat);
listusers(ptustat);

最佳答案

我将笨拙的 (*ptustat + i)).xxx 替换为等效的(但可读)ptustat[i].xxx

现在您对 strtok 的使用是错误且尴尬的。试试这个:

while (fgets(str, 100, fileu) != NULL)
{
strcpy(temp, str);
strcpy(ptustat[i].name, strtok(temp, "#"));
offset += (strlen(temp) + 1);
strcpy(temp, str + offset);
char *p = strtok(temp, "#");

if (p == NULL) // p can be NULL here
{
printf("BUMMER\n");
exit(1);
}

strcpy(ptustat[i].contact, p);
offset += (strlen(temp) + 1);
strcpy(temp, str + offset);
strcpy(ptustat[i].uname, strtok(temp, "#"));
offset += (strlen(temp) + 1);
strcpy(temp, str + offset);
strtok(temp, "#");
offset += (strlen(temp) + 1);
strcpy(temp, str + offset);
ptustat[i].saldo = atof(strtok(temp, "\n"));
i++;
}

我将修正错误作为练习。

此外(与您的问题无关):

可以替换

char* str = (char*) malloc(sizeof(char)*100);
...
free(str);

char str[100];

动态分配固定空间缓冲区通常是没有意义的。

关于C:strcpy 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43809204/

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