【发布时间】:2014-04-28 13:57:53
【问题描述】:
我遇到了一个奇怪的分段错误。我几乎忽略了它,因为它只在传递给函数的字符串以字母 v 或更大字母开头时出现。该程序由一个由 26 个链表指针组成的数组和一个函数组成,该函数创建一个新节点,对它们进行排序(使用另一个函数,然后将它们添加到链表数组中)。这是遇到分段错误的代码。
void sort(contact* newContact,int ind, contact** array[]){
contact* current; //pointer to current contact
//Case to test if the contact belongs at the head ###SEGMENTATION FAULT IF name begins with 'v'
if ((*array)[ind] == NULL || strcmp(&(*array)[ind]->name[0],&newContact->name[0])>0){
newContact->next=(*array)[ind]; // contect next pointer is equal to the pointer at index 'ind'
(*array)[ind]=newContact; //goes to array and change the pointer at the index 'ind'
}
else{
current=(*array)[ind]; //updates the current pointer to the first pointer in the index 'ind'
//finds the position to insert contact
while(current->next!=NULL&&strcmp(¤t->next->name[0],&newContact->name[0])<0){
current=current->next; //updates pointer if current is not NULL or current is smaller than new contact
}
//the loop will break at the insertion point.
//inserts contact
newContact->next=current->next;
current->next=newContact;
}
printf("ADDED\n");
}
这是创建节点的代码,以及在某处出错时收集输入的代码
void addContact(contact* list[]){
contact* new= malloc(sizeof(contact)); // creates new contact and allocates memory for it
printf("NAME: ");
new->name=GetInput(1); //saves the name
printf("NUMBER: ");
new->number=GetInput(0); //saves the number
int x=GetIndex(new->name);
contact** ptr=&list[x];
sort(new,x, &ptr);
printf("Contact Added!\n");
}
对于此函数,如果类型为 1,则确保输入的字符串以字母字符开头。如果没有,那就别管它了
char* GetInput(int type){
int loop=0;
char* buffer; //stores the entire input from the user
if (type==1){
do {
scanf("%ms",&buffer); //takes input from user
//checks if alphabetical
if (isalpha(buffer[0]))
loop=1;
else{
printf("Try again\nThe first character must be alphabetical\n");
free(buffer);
}
}
while(loop==0);
}
//when 1 isnt specified, the input is left untreated
else{
scanf("%ms",&buffer);
}
return buffer;
}
【问题讨论】:
-
分段错误是运行时错误,因此尝试执行“gdb”至少您会确切知道发生在哪些行分段错误。之后就可以轻松解决了。
-
我确实在 gdb 中运行过,这就是为什么我可以在代码中查明分段错误所在的原因,但我无法理解它是如何仅在 name[0] 字符为 v 或更大时出现分段错误的.它与除 v-z 中的字母外的其他字母完美配合
-
首先,您的
GetInput函数完全错误!!! 1.你没有初始化buffer变量,所以它很可能指向了一个无效的内存地址。 2. 你到底想在do/while循环中实现什么仍然是一个谜(检查第一个字符是否是字母?其他字符呢?)。 3.如果你想从用户那里扫描字符串,那么你应该用buffer的值调用scanf,而不是用buffer的地址buffer... -
您已将
array声明为contact ***,但您将其视为已声明为contact **(*)[N]。那会引起胃灼热。您需要退后一步,确保所有类型都同步。 -
@barakmanos scanf 将初始化缓冲区指针。使用 %ms 说明符,scanf 将 malloc 数据。在继续之前,我试图检查输入的第一个字符是否是字母。
标签: c arrays pointers linked-list segmentation-fault