I’d want to separate a string into 4 parts. What I need is basically this:
sscanf(string, "%d %d %d %[^\n]", id1, id2, id3, restOfString);
The var restOfString is a char*
Problem: restOfString must point to the smallest space of memory possible and still contain all the string indicated by the %[^\n].
I wanted just about what asprintf does. It has an internal malloc() that creates the memory space needed to print the string. I wanted the same technique for sscanf(). How can I accomplish that? How can I know the size of the string sscanf() will read?
I completely agree with RushPL about not bothering to micro-optimize for memory. In the more general case, though, where you might have a large string and comparatively small restOfString, here’s an approach that aliases
restOfStringto the main string:Basically, use %n to grab the current position while parsing, and then use that as an offset into the original string. Note that %n is a specifier that is very likely to cause format-string vulnerabilities if used carelessly. If you’re doing complicated parsing, you shouldn’t be using
scanfand friends.