我正在导航到strcat.asm文件的错误并在主循环入口处设置断点。我创建的readFile方法在字符串在此strlen循环中被标记化之前就已断开:
while( !feof(fptr) )
{
fgets(oneLine, CONTACT_MAX, fptr); // process the next line to be tokenized
if (oneLine[strlen(oneLine) - 1] == '\n')
{
oneLine[strlen(oneLine) - 1] = '\0';
}
sn = strtok(oneLine, " , ");
fn = sn ? strtok(NULL, " , ") : NULL;
ph = fn ? strtok(NULL, " , ") : NULL;
co = ph ? strtok(NULL, " , ") : NULL;
任何人都有任何想法,我在这里出错?
我的readFile()如下:
struct contact *readFile( struct contact *ptrList)
{
struct contact *head = NULL;
struct contact *newContact;
FILE *fptr;
char oneLine[CONTACT_MAX];
char *sn, *fn, *ph, *co;
head = ptrList;
//open test.csv to be read
fptr = fopen("test.csv", "r");
if( fptr == NULL )
{
printf("\nCouldn't open %s...", "test.csv");
return(ptrList);
}
fgets(oneLine, CONTACT_MAX, fptr);
while( !feof(fptr) )
{
fgets(oneLine, CONTACT_MAX, fptr); // process the next line to be tokenized
if (oneLine[strlen(oneLine) - 1] == '\n')
{
oneLine[strlen(oneLine) - 1] = '\0';
}
sn = strtok(oneLine, " , ");
fn = sn ? strtok(NULL, " , ") : NULL;
ph = fn ? strtok(NULL, " , ") : NULL;
co = ph ? strtok(NULL, " , ") : NULL;
if ( head == NULL )
{
head = (struct contact *)malloc(sizeof(struct contact));
ptrList = head;
strcpy(head->fName,fn);
strcpy(head->sName,sn);
strcpy(head->phone,ph);
strcpy(head->company,co);
head->prev = NULL;
head->next = NULL;
}
else
{
newContact = (struct contact *)malloc(sizeof(struct contact));
head->next = newContact;
newContact->prev = head;
newContact->next = NULL;
strcpy(newContact->fName, fn);
strcpy(newContact->sName, sn);
strcpy(newContact->phone, ph);
strcpy(newContact->company, co);
head = newContact;
} // end of (ptrList == NULL)
} // end of while( !feof(fptr))
fclose(fptr);
return(ptrList);
}
文件的格式如下:
姓氏,名字,号码,公司
Builder,Bob,1234567,Bob's
未知,瓢,8765645,Bob的
答案 0 :(得分:1)
head = (struct contact *)malloc(sizeof(struct contact));
ptrList = head;
strcpy(head->fName,fn);
strcpy(head->sName,sn);
strcpy(head->phone,ph);
strcpy(head->company,co);
在没有head
成员的情况下,您正在解除引用head
,这是未定义的行为,可能会导致您的错误,因为strcpy
期待\0
终止的数组。但由于你没有初始化头部成员,你无法知道它们是否被终止。即使它们是,strcpy()
必须阅读以检查\0
并且至于未初始化的问题,strcp()
仍在读取未初始化的内存。
最后一个标准的引用:
J.2未定义的行为
1在以下情况下,行为未定义:
[..]
使用malloc函数分配的对象的值(7.20.3.3)。
所以一个解决方案是memset()
前往0
所以即使你不覆盖它,所以memblock将在任何地方终止。