我正在使用鏈接列表示例from junghans並嘗試使其與某些服務器代碼一起工作 。在字符數組中,我可以插入一個主機(來自inet_ntoa) 並更新它的年齡。所以我可以發送一個數據包到守護進程,但是它會崩潰。 我試過設置next_pointer=start_pointer;
,因爲從我讀的內容來看,它會是 的一個循環列表。然而,接收第二包,strcpy的崩潰..首次遍歷後鏈接列表段錯誤
問題後:
- 如何我點開始,如果next_pointer = start_pointer不會做的伎倆?
- 在覆蓋char數組的成員之前,我需要釋放嗎?
struct x {
char name[20];
int age;
struct x *next_rec;
};
struct x *start_pointer;
struct x *next_pointer; // starting hosts, will be overwritten
char *names[] = {
"127.0.0.1",
"evil666",
"192.168.56.101",
""
};
int ages[] = {0,20,30,0};
// some other code
while (1) {
sleep(1);
us=time(NULL);
printf("%ld, Sleep a second\n", us);
buf[0] = 0x0;
current_host = 0x0;
memset (buf,0,sizeof buf);
if(recvfrom(s, buf, BUFLEN, 0, (struct sockaddr*)&si_other, &slen)==-1)
diep("recvfrom()");
current_host = inet_ntoa(si_other.sin_addr);
if(!current_host)
diep("inet_ntoa()");
/* linked list initialization */
/* Initalise 'start_pointer' by reserving
* memory and pointing to it
*/
start_pointer=(struct x *) malloc (sizeof (struct x));
if(!start_pointer)
diep("start pointer on holiday");
/* Initalise 'next_pointer' to point
* to the same location.
*/
next_pointer=start_pointer;
/* Put some data into the reserved
* memory.
*/
strcpy(next_pointer->name,current_host);
next_pointer->age = ages[count];
/* Loop until all data has been read */
while (ages[++count] != 0)
{
/* Reserve more memory and point to it */
next_pointer->next_rec=(struct x *) malloc (sizeof (struct x));
if(!next_pointer)
diep("next pointer on holiday");
strcpy(next_pointer->name, names[count]);
next_pointer->age = ages[count];
}
next_pointer->next_rec=NULL;
next_pointer=start_pointer;
/* insert new record, update age */
while (next_pointer != NULL)
{
printf("%s ", next_pointer->name);
if(strstr(next_pointer->name,current_host)) {
printf("%d \n", next_pointer->age+1);
}
if(!strstr(next_pointer->name,current_host)) {
printf("%d \n", next_pointer->age);
}
next_pointer=next_pointer->next_rec;
}
next_pointer=start_pointer; // XXX
哦,縮進使得它看起來更容易。 :)你確定count是否在數組邊界內? – 2012-03-02 11:31:19
什麼是計數?它在哪裏初始化? – wildplasser 2012-03-02 11:42:20
int count = 0; ... – Anton 2012-03-02 11:48:39