代码的用途: 要维护一个唯一的元素链接列表...UFID 是 unique 的关键字
Structure declaration:
struct sharedFiles
{
char UFID[50];
int valid; //valid 1 if someone have this file in write mode
int shared; //no of user's reading this file
struct sharedFiles *next; //pointer to next node
}*sfstart,*sfend; //sfstart points to the first node of linked list and efend to the last node of linked list so that it will be easy to just insert at the end without traversing the linked list
错误描述: 当我第二次调用下面的代码时,它给出了段错误。 我尝试使用 GDB 进行调试,它说无法访问该行的位置
if(strcmp(sftemp->UFID,ufid)==0)
在上面的行中,无法访问sftemp->UFID
/*Function code*/
int addShareList(char *ufid,int mode) //mode=0 (read) and mode=1 (Write request)
{
struct sharedFiles *sftemp,*newnode;
sftemp=sfstart;
if(sfstart==NULL) //if list is empty add first node
{
sfstart=(struct sharedFiles *) malloc(sizeof(struct sharedFiles));
strcpy(sfstart->UFID,ufid);
sfstart->valid=mode;
sfstart->shared=1;
sfstart->next=NULL;
sfend=sfstart; //this node will also be last node of Linked list
return 0;
}
else //if list is not empty
{
while(sftemp->next != NULL) //traverse till last node
{
if(strcmp(sftemp->UFID,ufid)==0)
{
//here if same node found some manupulation to the struct variables
}
sftemp=sftemp->next;
} //while
if(sftemp->next==NULL) //procvess last node
{
if(strcmp(sftemp->UFID,ufid)!=0) //if last node not same add node at the end of Linked list
{
newnode=(struct sharedFiles *) malloc(sizeof(struct sharedFiles));
strcpy(newnode->UFID,ufid);
newnode->valid=mode;
newnode->shared=1;
newnode->next=NULL;
sftemp->next=newnode;
sfend=newnode;
return 0;
}
else //if last node is same
{
//some manipulations to struct variables
}
} //if
}
return -1;
}//addShareList
上面的代码对于插入第一个元素效果很好。当我调用相同的函数在链表中插入第二个节点时,它无法在比较时访问第一个节点 在 if(strcmp(sftemp->UFID,ufid)==0) 行中。希望现在代码的目的很清楚。
提前致谢..
最佳答案
在while中,您检查是否sftemp!=NULL,以便我们可以确定在第二次迭代中,在行sftemp=sftemp->next;之后指针包含分配的内存。
但是,由于我不知道列表的结构,我无法确定内容是否包含另一个 sharedFiles 类型的节点,它可能包含一个 end-list不包含UFID属性的节点。
因此,检查您的列表如何控制列表是否完成。
另一个解决方案可以是这样更改您的支票:
while(sftemp->next!=NULL)
...
if(sftemp->next==NULL) {
//add the node in the right way, consider the end-list node
}
编辑:
此外,将第一个 if 行 sftemp->next = NULL; 更改为 sfnext->next = NULL;。
并且一定要初始化stnext = NULL。
编辑2:
既然你发布了结构声明,我仍然看不到你何时初始化sfstart。尝试这样做:
Structure declaration:
struct sharedFiles
{
char UFID[50];
int valid; //valid 1 if someone have this file in write mode
int shared; //no of user's reading this file
struct sharedFiles *next; //pointer to next node
}*sfstart = NULL,*sfend;
关于c - 无法访问内存 0X....C 程序(Ubuntu 12.10),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15248896/