【发布时间】:2012-11-26 00:10:41
【问题描述】:
我在编写一个从文件中提取字符串作为更大程序的一部分的函数时遇到了一些问题。一切似乎都运行良好,除非我使用 memset 或 bzero 擦除我一直在使用的字符数组。我已经解决这个问题一个多小时了,无论我做什么,我都会遇到段错误。我在 bzero 和 memset 上都收到了这个错误。请帮帮我。 我在下面附上我的代码。打印了“Come out of addfront”语句,但没有打印“Done with all bzero”语句。那时我遇到了分段错误。谢谢
void extractFileData(FILE *fp , char clientName[])
{
char tempFileName[50], tempFilePath[100], tempFileSize[50];
struct stat fileDetails;
while(fgets(tempFileName, sizeof(tempFileName), fp)!= NULL)
{
if((newLinePos = strchr(tempFileName, '\n')) != NULL)
{
*newLinePos = '\0';
}
strcat(tempFilePath, "SharedFiles/");
strcat(tempFilePath, tempFileName);
if(stat(tempFilePath, &fileDetails) < 0)
{
perror("Stat error");
exit(1);
}
//Copy it into a string
sprintf(tempFileSize, "%zu", fileDetails.st_size);
printf("temp file size: %s\n", tempFileSize);
//Add all these details to the file list by creating a new node
addFront(tempFileName, tempFileSize, clientName);
printf("Come out of addfront\n");
memset(&tempFileName, 0, 45);
printf("Done with all bzero\n");
memset(&tempFileSize, 0, sizeof(tempFileSize));
memset(&tempFilePath, 0, sizeof(tempFilePath));
printf("Done with all bzero\n");
}
}
编辑:
void addFront(char fileName[], char fileSize[], char clientName[])
{
FILENODE* n;
printf("Inside add front function\n");
strcpy(n->fileName, fileName);
printf("n->filename: %s\n", n->fileName);
strcpy(n->fileSize, fileSize);
printf("n->filesize: %s\n", n->fileSize);
strcpy(n->ownerName, clientName);
printf("n->ownername: %s\n", n->ownerName);
myFileList.head = n;
printf("Did it go past myfilelist head = n\n");
myFileList.numOfNodes++;
printf("num of nodes: %d\n", myFileList.numOfNodes);
}
我已经为 addFront 函数添加了我的代码。它基本上增加了
struct myFileList 的详细信息,它基本上是一个实现
的一个链表。 FILENODE 代表列表中的每个条目。
编辑:
添加我正在使用的结构
struct fileNode
{
char fileName[50];
char fileSize[50];
char ownerName[25];
struct fileNode* next;
};
struct fileList
{
struct fileNode* head;
struct fileNode* tail;
int numOfNodes;
};
typedef struct fileList FILELIST;
typedef struct fileNode FILENODE;
【问题讨论】:
-
addFront 是做什么的?顺便说一句:当你做
strcat(tempFilePath, "SharedFiles/");tempFilePath 时没有初始化。在某处可能是也可能不是 \0。 -
顺便说一句:你应该尽可能避免使用 strcat 。我的建议是将两个 strcat() 调用合并为一个
ret = snprintf(tempFilePath, sizeof tempFilePath,"%s/%s", "SharedFiles", tempFileName);调用。 -
您的
strcat确实很糟糕。但是没有语言级别的原因您的代码会在那些memsets 上崩溃。如果确实如此,我看到的唯一可能性是addFront以某种方式破坏了程序堆栈结构,仍然允许它成功返回您的函数,但导致它在第一个memset时崩溃。 -
未初始化的 tempFilePath + 随后的 strcat() 怎么样?甚至在调用神秘的 addFront() 之前,损坏可能已经造成。
-
感谢您的所有 cmets/输入。
tempFilePath似乎工作正常,因为我在将其传递给stat()调用之前将其打印出来进行了测试。由于stat()调用工作正常,我猜tempFilePath,至少在这一点上,似乎没问题。但我会确保我更改它以避免大家提到的关于在未初始化的变量上使用strcat的问题。
标签: c segmentation-fault memset