我有一个简单的 c 应用程序,我有服务器,我首先运行它,然后尝试执行我的 c 程序,我得到这个错误分段错误核心转储。我认为问题可能来自我的分配内存,但不知道它是否来自那里如何修复它: Bellow 是我的代码:
/* This is student.c file which as a part of MAD assignment 1 is referenced and used in main.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "config.h" // auto generated
#include "customer.h"
Customer *make_customer(unsigned id)
{
Customer *cust;
if ((cust = (Customer *)malloc(sizeof(Customer))) == NULL) {
fprintf(stderr, "Failed to allocate Customer structure!\n");
exit(EXIT_FAILURE);
}
cust->active = 0;
cust->id = id;
cust->old = NULL;
cust->address = NULL;
cust->name = NULL;
return cust;
}
void free_customer(Customer *cust)
{
free(cust->old);
free(cust->address);
free(cust->name);
free(cust);
}
void make_customer_active(Customer *cust)
{
cust->active = 1;
}
void set_customer_old(Customer *cust, char *old)
{
cust->old = strdup(old);
}
void set_customer_address(Customer *cust, char *address)
{
cust->address = strdup(address);
}
void set_customer_name(Customer *cust, char *name)
{
cust->name = strdup(name);
}
int is_customer_active(Customer *cust)
{
return cust->active;
}
int serialize_customer(char *buffer, Customer *cust)
{
size_t offset = 0;
memcpy(buffer, &cust->id, sizeof(cust->id));
offset = sizeof(cust->id);
memcpy(buffer+offset, &cust->active, sizeof(cust->active));
offset = offset + sizeof(cust->active);
memcpy(buffer+offset, cust->old, strlen(cust->old)+1);
offset = offset + strlen(cust->old)+1;
memcpy(buffer+offset, cust->address, strlen(cust->address)+1);
offset = offset + strlen(cust->address)+1;
memcpy(buffer+offset, cust->name, strlen(cust->name)+1);
offset = offset + strlen(cust->name)+1;
return offset;
}
int deserialize_customer(char *buffer, Customer *cust)
{
size_t offset = 0;
memcpy(&cust->id, buffer, sizeof(cust->id));
offset = sizeof(cust->id);
memcpy(&cust->active, buffer+offset, sizeof(cust->active));
offset = offset + sizeof(cust->active);
memcpy(cust->name, buffer+offset, strlen(buffer+offset)+1);
offset = offset + strlen(buffer+offset)+1;
return offset;
}
void print_customer(Customer *cust)
{
printf("Customer id:%d\n", cust->id);
printf("Cutomer age:%s\n", cust->old);
printf("Cutomer name:%s\n", cust->name);
printf("Cutomer address:%s\n", cust->address);
}
Customer *alloc_blank_customer()
{
Customer *cust;
if ((cust = (Customer *)malloc(sizeof(Customer))) == NULL) {
fprintf(stderr, "Failed to allocate Customer structure!\n");
exit(EXIT_FAILURE);
}
cust->active = 0;
cust->id = 0;
if ((cust->name = malloc(MAX_NAME)) == NULL) {
fprintf(stderr, "Failed to allocate name!\n");
exit(EXIT_FAILURE);
if ((cust->old = malloc(MAX_OLD)) == NULL) {
fprintf(stderr, "Failed to allocate age!\n");
exit(EXIT_FAILURE);
if ((cust->address = malloc(MAX_ADDRESS)) == NULL) {
fprintf(stderr, "Failed to allocate address!\n");
exit(EXIT_FAILURE);
}
return cust;
}}}