Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.
This repository was archived by the owner on Jan 21, 2026. It is now read-only.

Quadratic time and memory use on very deep trees #393

Description

@DemiMarie

The following program takes O(n^2) time (but not memory) for very large arguments. I suspect one needs #392 applied to notice (otherwise, one hits a stack overflow first).

#include <ctype.h>
#include <gumbo.h>
#include <stdint.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv) {
  if (argc != 2) {
    fputs("Must have exactly one argument: depth of tree to make\n", stderr);
    return 1;
  }
  char *endp;
  unsigned long long q = strtoull(argv[1], &endp, 0);
  const size_t maxarg = (SIZE_MAX - 9) / sizeof "<i>";
  if (q > maxarg) {
    fprintf(stderr, "Argument too large!  Must be at or below %zu\n", maxarg);
    exit(1);
  }
  if (*endp) {
    fprintf(stderr, "Trailing junk at end of argument!\n");
    exit(1);
  }
  char *buf = malloc(q * (2*sizeof "<i>" - 1) + sizeof "<i>\n");
  if (!buf) {
    fputs("Out of mem allocating buffer!\n", stderr);
    return 1;
  }
  char *bufptr = buf;
  memcpy(bufptr, "<i>\n", 4);
  bufptr += 4;
  for (size_t i = 0; i < q; ++i) {
    memcpy(bufptr, "<i>", 3);
    bufptr += 3;
  }
  for (size_t i = 0; i < q; ++i) {
    memcpy(bufptr, "</i>", 3);
    bufptr += 4;
  }
  GumboOptions options;
  memcpy(&options, &kGumboDefaultOptions, sizeof options);
  options.max_errors = 50;
  GumboOutput *output = gumbo_parse_with_options(&options, buf, strlen(buf));
  if (!output) {
    fputs("Out of mem while parsing!\n", stderr);
    free(buf);
    return 1;
  }
  gumbo_destroy_output(&kGumboDefaultOptions, output);
  free(buf);
  return 0;
}

perf reveals that the time is spent in reconstruct_active_formatting_elements.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions