c - Segmentation fault with malloc on char* in struct -
i'm teaching myself c , fun thought cool write little web framework. code i'm working on @ moment registering routes/handlers.
i've run segmentation fault malloc, strangely on 4th time called. i've marked point in code segmentation fault occurs. i'm not sure how debug other wrapping areas of code printfs , putss. i've tried using valgrind debug this, segmentation fault doesn't happen when run valgrind. valgrind does tell me there memory leak stemming same malloc, though. i'm doing wrong there, don't know what.
fyi, destroy_routes called before kid process terminated.
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 segmentation fault occurs on 4th 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 = 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); }
you missed set next pointer null. issue.
route->method = method; route->handler = handler; route->next = null; c linked-list segmentation-fault malloc
No comments:
Post a Comment