繁体   English   中英

struct char *上的malloc出现分段错误

[英]Segmentation fault with malloc on char* in struct

我正在自学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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM