understanding calloc

So don't bother trying to understand the point of this program. it's more of a structured learning exercise. My question is, why does this work
assuming argument 1 is between 1 and 55 bytes, calloc is instructed to create a an array of 64 elements. Why then does this for loop not create a segmentation fault? It seems to allow me to overrun the array I created.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <cassert>
#include <cmath>
typedef unsigned int bitsize_t;
typedef unsigned int bytesize_t;
using namespace std;
int main(int argc, char** argv)
{
    	assert(argv[1] != NULL );
    	char* padding;
    	bytesize_t M = strlen(argv[1]);
		bitsize_t l = 8 * M;
		const float blocks = ceil(( (float)l + 1. + 64. ) / 512 );
		const unsigned int block_length = 512 *blocks / 8;
		padding = (char*)calloc(block_length, sizeof(char));
		memcpy(padding,argv[1],M);
		padding[M]=0x67;
		for(int i = (M+1); i < block_length+100; i++) padding[i]=0x66;
		cout << "-->"<<padding<<"<--"<<endl;	
        return 0;
One of the possible manifestations of undefined behavior is "nothing is happening".

Try executing your program with valgrind and you'll see a few screenfuls of errors:

$ valgrind ./test abcd
...
==10572== LEAK SUMMARY:
==10572==    definitely lost: 64 bytes in 1 blocks
...
==10572== ERROR SUMMARY: 231 errors from 16 contexts (suppressed: 2 from 2)
Thanks, I wasn't familiar with that.
Topic archived. No new replies allowed.