导致C中分段错误的fprintf
错误行位于底部函数的最后几行。我已经把我的错误缩小到fprintf的行,我知道SEG故障并不是与这些代码行同时出现的,另一个线程实际上是造成问题的原因,因为我进一步调试了printf行,在不同的时间间隔使用sleep函数,以便通过估计SEG故障发生的时间以及手动设置的时间间隔来验证错误源介意瞧,如果我使用sleep(3)而不是Caps中的注释,SEG故障会在3秒钟后出现 测试输入和缓冲区,即“缓冲区”,因此包含:“创建迷迭香10密码” 结构定义:导致C中分段错误的fprintf,c,file,printf,C,File,Printf,错误行位于底部函数的最后几行。我已经把我的错误缩小到fprintf的行,我知道SEG故障并不是与这些代码行同时出现的,另一个线程实际上是造成问题的原因,因为我进一步调试了printf行,在不同的时间间隔使用sleep函数,以便通过估计SEG故障发生的时间以及手动设置的时间间隔来验证错误源介意瞧,如果我使用sleep(3)而不是Caps中的注释,SEG故障会在3秒钟后出现 测试输入和缓冲区,即“缓冲区”,因此包含:“创建迷迭香10密码” 结构定义: typedef struct {
typedef struct {
struct sockaddr_in addr;
int sock_fd;
char name[16];
time_t time_since_last_msg;
room *current_room;
} client;
void create_new_room(client* cli, char buffer[]) {
pthread_mutex_lock(&mutex);
printf("START create_new_room()\n");
char room_name[16], password[16], *token;
int capacity;
room *new_room = malloc(sizeof(new_room));
pthread_t tid;
FILE *rooms = NULL;
if((rooms = fopen("room-info.txt", "a")) == NULL) {
perror("Failed to open file.");
exit(-1);
}
token = strtok(buffer, " ");
token = strtok(NULL, " ");
strcpy(room_name, token);
token = strtok(NULL, " ");
capacity = atoi(token);
token = strtok(NULL, " ");
strcpy(password, token);
FD_ZERO(&(new_room->write_set));
strcpy(new_room->room_name, room_name);
new_room->room_id = ++natural_id;
add_room(new_room);
sleep(3);
// WTF IS GOING ON HERE?!?!?!
fprintf(rooms, "%s\n", room_name);
fprintf(rooms, "id=%u\n", natural_id);
fprintf(rooms, "owner=%s\n", cli->name);
fprintf(rooms, "capacity=%d\n", capacity);
fprintf(rooms, "pass=%s\n\n", password);
功能:
typedef struct {
struct sockaddr_in addr;
int sock_fd;
char name[16];
time_t time_since_last_msg;
room *current_room;
} client;
void create_new_room(client* cli, char buffer[]) {
pthread_mutex_lock(&mutex);
printf("START create_new_room()\n");
char room_name[16], password[16], *token;
int capacity;
room *new_room = malloc(sizeof(new_room));
pthread_t tid;
FILE *rooms = NULL;
if((rooms = fopen("room-info.txt", "a")) == NULL) {
perror("Failed to open file.");
exit(-1);
}
token = strtok(buffer, " ");
token = strtok(NULL, " ");
strcpy(room_name, token);
token = strtok(NULL, " ");
capacity = atoi(token);
token = strtok(NULL, " ");
strcpy(password, token);
FD_ZERO(&(new_room->write_set));
strcpy(new_room->room_name, room_name);
new_room->room_id = ++natural_id;
add_room(new_room);
sleep(3);
// WTF IS GOING ON HERE?!?!?!
fprintf(rooms, "%s\n", room_name);
fprintf(rooms, "id=%u\n", natural_id);
fprintf(rooms, "owner=%s\n", cli->name);
fprintf(rooms, "capacity=%d\n", capacity);
fprintf(rooms, "pass=%s\n\n", password);
线路
room *new_room = malloc(sizeof(new_room));
这是错误的。您只为指针分配了一个空间,而结构需要一个空间
应该是
room *new_room = malloc(sizeof(*new_room));
或
问题:
malloc(sizeof(new_room))
另一个证据表明,对于未定义的行为,人们不应该匆忙得出导致它的原因的结论。