jeudi 1 juin 2017

Reliable way to place char directly after array

I'm using following code to read from socket:

char buf[4097];
int ret = read(fd, buf, sizeof(buf) - 1);
buf[ret] = 0x0;
std::cout << buf << "\n";

However, I don't like the need for 4097 and sizeof(buf) - 1 in there. It's that kind of stuff that's easy to forget. So I wonder, is there some nice way to force compiler to but 0x0 directly on stack right after the array?

What I would love is something like

char buf[4096];
char _ = 0x0;

but I have no idea how to force compiler to not but anything in between (afaik #pragma pack works only on structures, not on stack).

Aucun commentaire:

Enregistrer un commentaire