所以我对我的RPC程序做了一些更新,现在它的分段错误,我不知道我做错了什么。两者的区别在于删除了为args结构赋值的if语句。
分段故障
void
database_1(char *host, char *action, char *message)
{
printf("Action: %s\n", action);
printf("Message: %s\n", message);
CLIENT *clnt;
rpc_args *result_1;
//struct rpc_args action_1_arg;
//rpc arguments struct to pass to server
struct rpc_args *args = malloc(sizeof(struct rpc_args));
char *id = generate_id();
if (strcmp(action, "GET") == 0) {
strcpy(args->action, action);
strcpy(args->id, id);
} else if(strcmp(action, "PUT") == 0) {
strcpy(args->action, action);
strcpy(args->id, id);
strcpy(args->message.content, message);
}
#ifndef DEBUG
clnt = clnt_create (host, DATABASE, ASSIGNMENT_7, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */
result_1 = action_1(args, clnt);
if (result_1 == (rpc_args *) NULL) {
clnt_perror (clnt, "call failed");
}
#ifndef DEBUG
free(args);
clnt_destroy (clnt);
#endif /* DEBUG */
}SegFault不
void
database_1(char *host, char *action, char *message)
{
printf("Action: %s\n", action);
printf("Message: %s\n", message);
CLIENT *clnt;
rpc_args *result_1;
//struct rpc_args action_1_arg;
//rpc arguments struct to pass to server
struct rpc_args *args = malloc(sizeof(struct rpc_args));
char *id = generate_id();
#ifndef DEBUG
clnt = clnt_create (host, DATABASE, ASSIGNMENT_7, "udp");
if (clnt == NULL) {
clnt_pcreateerror (host);
exit (1);
}
#endif /* DEBUG */
result_1 = action_1(args, clnt);
if (result_1 == (rpc_args *) NULL) {
clnt_perror (clnt, "call failed");
}
#ifndef DEBUG
free(args);
clnt_destroy (clnt);
#endif /* DEBUG */
}发布于 2016-04-26 22:29:08
您没有向我们展示struct的定义,但请确保它看起来如下所示:
#define MAX_STRING_SIZE 128
struct rpc_args {
/* other members here */
char action[MAX_STRING_SIZE];
char id[MAX_STRING_SIZE];
};同样,在struct中使用的args->message.content也必须以这种方式定义。
如果使用上述实现,请确保检查要复制的字符串的长度小于MAX_STRING_SIZE - 1。
或者,在将strcpy使用到这些成员之前,您可以用malloc动态地为字符串分配空间,然后在清理结构时使用free。
https://stackoverflow.com/questions/36876673
复制相似问题