r/cprogramming • u/SheikHunt • Jul 08 '26
Use the existing OS buffer, or your own
This is a fairly simple question:
You're on a Unix-like (for me, Linux), and you've got a File Descriptor that leads to some data. You don't know the length of the data (it's a TCP socket you're listening on), all you know is that it is ready to be read.
Do you:
A) Read an absurd amount of bytes of data into a (sufficiently large + 1) char array of your own, and if it overflows, handle it with mallocated memory or just reject the connection (like a monster)
Or
B) Just use existing kernel system calls to read and parse the data as necessary.
For context: this is about an HTTP server, and I have an internal string_t struct that I use for parsing, which needs a byte-length to be usable
5
u/flyingron Jul 08 '26
What syscalls do you have in mind? But if it works for you can fdopen the socket fed into a stdio stream.
4
u/ScallionSmooth5925 Jul 08 '26
I usually read in the first 4k block or whatever much is available and based on that continue reaching when needed
2
u/TheKiller36_real Jul 08 '26
just stream it using
readcalls (or better,io_uring) and if you actually need to have something in memory all at once may I suggest that HTTP indicates the length of the data!? if you dislike that stream it into a growable array and suffer therealloccalls I guess1
u/makzpj Jul 08 '26
Not quite sure I understand your question. For me it’s about what are you doing with that data. Depending on the destination you’ll design your program in a way or another way.
1
u/Interesting_Buy_3969 Jul 13 '26
You can use
mmapif size of the data to be read is seriously large, which I assume is unlikely to be the case if it's an HTTP package, so that would be overkill there. I'd just usereadwith the necessary socket.