The basic idea is simply this - I start off with "pointer", which points to a chunk of memory suitable for storing 100 integers. I want to eventually store 1000 consecutive integers in a contiguous chunk of memory, but I don't know this in advance so I want to steadily grow that 100 int chunk up to 1000 in 100 integer intervals. I check the return value of "realloc" to make sure nothing goes wrong at any of these intervals.

When I compile the code above (with a simple "gcc realloctest.c -o realloctest", no optimisations or the like), everything seems to run smoothly. My output ends with:

and if I grep the output for the word "memory" I see 9 lines of "Good memory stuff!", suggesting that realloc is doing its job properly each time.

Now for the problematic part:

If I run this very same program through Valgrind (with "valgrind --leak-check=yes ./realloctest"), things do not run anywhere near as smoothly. Around the time of the first call to "realloc" I see this:

Can someone please advise me on what's going wrong, here? I am baffled by the supposed "illegal write" when storing the 101st integer. Valgrind claims that "Address 0x417a1b8 is not stack'd, malloc'd or (recently) free'd", but the presence of a "Good memory stuff!" immediately before that line suggests to me that the relevant address certainly should have been properly allocated.

Thanks in advance to anyone who can help me on this, if more information is needed to diagnose the problem, just ask!

Duh, what a stupid mistake. Thanks ephemera! This has, of course, fixed things perfectly and valgrind now reports zero errors. I think I'll make a habit of avoiding calloc in favour of malloc in future on account of this, so that always using sizeof becomes a habit.