gpt4 book ai didi

c - struct 中 char* 上的 malloc 的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 05:57:38 25 4
gpt4 key购买 nike

我正在自学 C,为了好玩,我认为编写一个小型 Web 框架会很酷。我目前正在处理的代码用于注册路由/处理程序。

我遇到了 malloc 的段错误,但奇怪的是它只在第四次被调用时出现。我已经在代码中标记了发生段错误的位置。除了用 printfputs 包装代码区域外,我不确定如何调试它。我试过使用 valgrind 来调试它,但是当我运行 valgrind 时段错误实际上并没有发生。不过,Valgrind 确实告诉我,同一 malloc 存在内存泄漏。所以很明显我在那里做错了什么,但我不知道是什么。

仅供引用,destroy_routes 在子进程终止之前被调用。

struct route {
char *path;
enum method method;
int(*handler)(struct request *, int sock);
struct route *next;
};


static struct route *routes;

void
register_route(char *path, enum method method,
int(*handler)(struct request *, int))
{
struct route *route;

if (routes == NULL)
routes = route = malloc(sizeof(struct route));
else {
route = routes;
while (route->next)
route = route->next;

route->next = malloc(sizeof(struct route));
route = route->next;
}

route->path = malloc((strlen(path) + 1) * sizeof(char)); /* <== HERE is where the segmentation fault occurs only on the fourth time */
strcpy(route->path, path);

route->method = method;
route->handler = handler;

printf("route created: %s, %i, %p\n", route->path, route->method, (void *)route->handler);
}

void
destroy_routes()
{
struct route *prev;
int i = 0;
while (routes) {
free(routes->path);
prev = routes;
routes = routes->next;
free(prev);
i++;
}
printf("destroyed %i routes\n", i);
}

void
register_routes()
{
register_route("/post", GET, &do_something);
register_route("/post", POST, &do_something_else);
register_route("/post/:id", GET, &do_something);
register_route("/post/:id/children", POST, &do_something_else);
}

最佳答案

您没有将 next 指针设置为 NULL。这可能是问题所在。

route->method = method;
route->handler = handler;
route->next = NULL;

关于c - struct 中 char* 上的 malloc 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24343476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com