-2
我想知道,如果有人可以幫助我這個段錯誤,Valgrind的和gdb點到的strcpy(),但我仍然無法找到它..C:分段故障與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);
}
userstat definiton:
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);
請提供[MCVE]。 – EOF
請至少展示'userstat'的定義,並顯示你如何調用'listusers',問題的根源就在那裏。 –
@MichaelWalz:考慮到'strtok()'不正確或至少不常用,我不確定這是否是「最可能」的問題。 – EOF