#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char String[256];
typedef struct LinkedListNode {
String Name;
struct LinkedListNode * Next;
struct LinkedListNode * Friend;
} Node;
typedef Node * NodePointer;
NodePointer InputData(NodePointer Head) {
String PersonName;
NodePointer Person;
int StringLength;
String FormattedName;
do {
printf("Enter nation name :");
fgets(PersonName,256,stdin);
if (PersonName[0] != '\n') {
Person = (NodePointer)malloc(sizeof(NodePointer));
//copy all except trailing \n
strncpy(Person->Name, PersonName, strlen(PersonName)-1);
Person->Next = Head;
Person->Friend = NULL;
Head = Person;
}
} while (strcmp(PersonName, "\n"));
return Head;
}
void InputAllies(NodePointer Head) {
String AllyName;
NodePointer Ally;
String FormattedName;
do {
printf("Enter best ally for %s :", Head->Name);
fgets(AllyName,256,stdin);
if (AllyName[0] != '\n') {
Ally = (NodePointer)malloc(sizeof(NodePointer));
//copy all except trailing \n
strncpy(Ally->Name, AllyName, strlen(AllyName)-1);
Head->Friend = Ally;
Head = Head->Next;
}
} while (Head != NULL);
}
段错误的具体部分是 InputAllies() 函数,并且仅适用于包含 5 个或更多元素的列表。我真的不知道发生了什么,但我认为这与我的字符串大小有关。减小 typedef String 的大小会在仅 3 个元素后导致段错误。
最佳答案
我认为在函数 InputData
中,就在 strncpy
之后,您忘记将最后的 '\0'
添加到字符串中人->姓名
。问题是当您打印字符串时。在您的 Mac 上,似乎有一个空字符恰好神奇地出现在正确的位置;在 Linux 服务器上,你就没那么幸运了。
从 manual 复制:
The
strcpy()
function copies the string pointed to bysrc
, including the terminating null byte ('\0'
), to the buffer pointed to bydest
. The strings may not overlap, and the destination string dest must be large enough to receive the copy.The
strncpy()
function is similar, except that at mostn
bytes ofsrc
are copied. Warning: If there is no null byte among the firstn
bytes ofsrc
, the string placed indest
will not be null-terminated.
所以你的问题是最后一句话,只有当你的源字符串不能放入目标字符串的前 n
个字节时才会发生。我认为这正是您的情况,因为您将 n
设置为小于源字符串的 strlen
。无论如何,您的代码中也可能存在其他错误。使用调试器或 valgrind 检查。
顺便说一句,我不明白你为什么要在那里使用 strncpy
,因为你的源字符串和目标字符串的长度必须相同。为什么不改用 strcpy
?
关于c - 为什么这段代码在我的笔记本电脑 (OSX 10.9) 上运行良好,但在服务器 (Linux) 上却出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19717297/