CHAPTER 6Strings and Memory
Memory is where C programs usually go wrong, and where cgull programs mostly don't, because of one decision about how they are run. This chapter explains that decision, and then the functions that make strings.
6.1 One Request, One Instance
Each request runs in a new instance of the program. It starts with
fresh memory, its globals at their initial values, and runs from the top
of main. When the response has been sent, the instance is
discarded. A second request, even one arriving a moment later, knows
nothing of the first.
This has three consequences. Nothing needs freeing, as the next section explains. A bug that corrupts memory spoils one response, not every response after it. And a program can't remember anything between requests in a global variable; whatever must last has to live somewhere else, such as a cookie, the URL, or, in time, a database.
Starting an instance is cheap: the compiled code is shared, and only the memory is new. For a program of moderate size it takes a fraction of a millisecond.
6.2 Never Free
A cgull program allocates as it likes, with malloc or
with the library's functions, and frees nothing. The memory is
reclaimed all at once, by discarding the instance, when the request ends.
Every string the library returns is valid until then, so there is no
question of who owns what:
char *title = cg_sprintf("%s: page %ld", cg_esc(name), page);
cg_printf(res, "<title>%s</title><h1>%s</h1>", title, title);
/* no free(title) */
You may still call free on what you got from
malloc, and in a loop that allocates a great deal it is
worth doing. But don't free anything a cg_ function
returned; those belong to the library.
6.3 Escaping
Text has to be escaped for the place it is going, and there are three
functions for the three usual places. Each returns a new string, and each
treats NULL as an empty string, so a missing parameter
needs no special case.
cg_esc is for HTML. It replaces &,
<, >, " and ' with
entities, which makes text safe both between tags and inside quoted
attribute values:
cg_printf(res, "<input name=q value=\"%s\">", cg_esc(cg_query(req, "q")));
cg_json_str is for JSON. It returns the string as a JSON
string literal, with the quotes around it, escaping quotes, backslashes and
control characters:
cg_json(res, 200, cg_sprintf("{\"q\":%s}", cg_json_str(cg_query(req, "q"))));
/* ?q=say+"hi" gives {"q":"say \"hi\""}
no q at all gives {"q":""} */
cg_url_encode is for URLs. It percent-encodes every byte
except letters, digits, and -_.~, which suits one path segment
or one query value:
cg_printf(res, "<a href=\"/search?q=%s\">", cg_url_encode(term));
A link built that way and put into HTML needs cg_esc as well
only if parts of it weren't encoded; an encoded string contains nothing that
HTML treats specially.
6.4 Building Strings
cg_sprintf formats as printf does, into a new
string of exactly the right length. It replaces the usual dance with
snprintf and buffers of a guessed size:
const char *where = cg_sprintf("/books/%s/chapters/%d", cg_url_encode(id), n);
The standard library is all there, too: string.h,
ctype.h, stdlib.h, math.h and the
rest come with wasi-sdk.
6.5 Limits
A Worker has 128 MB of memory, which the program's memory shares with
everything else in the Worker. The program's memory starts small and grows
as it allocates. If it can't grow, the library's functions abort and the
request gets a 500; malloc returns NULL, as
always.
The stack is 64 KB, which is less than you may be used to. A large local
array, or deep recursion, can overflow it, and the request gets a 500. Put
big buffers on the heap with malloc, or ask for a bigger stack
in package.json:
"cgull": { "ldflags": ["-Wl,-z,stack-size=1048576"] }
Exercise 6-1. A global counter, incremented by every request: what does it show? Write the handler and see.
Exercise 6-2. Write a function that returns a string of
n stars, built with malloc. Should it be freed?