Why does mprobe fail when checking string literals?

JSO*_*ody 0 c gcc memory-management heap-memory

In an effort to ensure a data structure that I implemented is functionally sound, I wrote a test file utilizing mcheck to be certain that I am working within the bounds of allocated memory. However when trying to use mprobe() on a string literal (and calling mcheck(NULL) at the beginning), the program always aborts with MCHECK_HEAD.

I tried this with the smallest program I can conceive:

#include <mcheck.h>
#include <stdio.h>

int main()
{

    mcheck(NULL);
    mprobe("test");

    exit(0);

}
Run Code Online (Sandbox Code Playgroud)

The result is the following:

#include <mcheck.h>
#include <stdio.h>

int main()
{

    mcheck(NULL);
    mprobe("test");

    exit(0);

}
Run Code Online (Sandbox Code Playgroud)

So it seems that mcheck fails whenever it encounters a string literal, thinking that preceding memory has been modified. Why? Is it because the string isn't explicitly malloced?

Ant*_*ala 5

enum mcheck_status mprobe(void *ptr);
Run Code Online (Sandbox Code Playgroud)

[...]

The mprobe() function performs a consistency check on the block of allocated memory pointed to by ptr.

A string literal is not a pointer to allocated memory. The C standard very strictly defines allocated storage as that which is allocated with malloc, calloc, realloc and the like. POSIX extends the list e.g. with strdup. A string literal, on the other hand, is a non-modifiable array of characters with static storage duration, though it does not have a const element type which is why you didn't get a warning. Try:

char *foo = "test";
const char *bar = "test";
mprobe(foo);
mprobe(bar);
Run Code Online (Sandbox Code Playgroud)

and the compiler reports a constraint violation compiling the latter call:

<source>: In function 'main':
<source>:12:12: warning: passing argument 1 of 'mprobe' discards 'const' qualifier
from pointer target type [-Wdiscarded-qualifiers]
   12 |     mprobe(bar);
      |            ^~~
In file included from <source>:1:
/usr/include/mcheck.h:53:41: note: expected 'void *' but argument is of
type 'const char *'
   53 | extern enum mcheck_status mprobe (void *__ptr) __THROW;
      |                                   ~~~~~~^~~~~
Run Code Online (Sandbox Code Playgroud)