I wrote a function to add items to my log file. Variables loglevs[]
and des
together exceed 30 characters (by far). When I use the function as below, all works fine.
char *logitem (int loglev, const char *des) {
extern const char *loglevs[];
char *lld; // loglevel & description total 28 characters (7+1+20)
lld = (char *) malloc((29) * sizeof(char));
snprintf(lld, 29, "[%5s] %s", loglevs[loglev], des);
return lld;
}
However when I use malloc(24)
instead of malloc(29)
, I get the following error:
root@vm:/home/geohei/devel# prog
*** Error in `prog': malloc(): memory corruption: 0x0000000000853330 ***
Aborted (core dumped)
I was expecting to get the error already at malloc(28)
. Why is it only showing at malloc(24)
? Actually, I can go down to malloc(25)
before the error pops up.
I confirmed the test multiple times.