在struct*中的mall*上使用malloc进行分段错误

tjb*_*982 0 c malloc linked-list segmentation-fault

我正在教自己C和有趣的我认为写一个小的Web框架会很酷.我目前正在处理的代码是注册路由/处理程序.

我遇到了一个分段错误malloc,但奇怪的是只在第四次被调用时.我在代码中标记了发生分段错误的点.除了用printfs和putss 包装代码区域之外,我不确定如何调试它.我尝试使用valgrind来调试它,但是当我运行valgrind时,实际上并没有发生分段错误.Valgrind 确实告诉我,同样存在内存泄漏malloc.显然我在那里做错了,但我不知道是什么.

destroy_routes仅在子进程终止之前调用FYI .

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);
}
Run Code Online (Sandbox Code Playgroud)

use*_*104 5

您错过了将next指针设置为NULL.这可能是个问题.

route->method = method;
route->handler = handler;
route->next = NULL;
Run Code Online (Sandbox Code Playgroud)