trying to find number of caches on a machine

I am trying to find the number of caches on a machine programatically.

#include <stdio.h>
#include <malloc.h>

int main(void)
{
int *ptr,*ptr1,i,j;
j=0;
i=1;
printf("Changing allocation with brk()\n");
while(1)
{

    for\(j=0;j&lt;i;j\+\+\)
    \{
	    ptr = \(int *\) malloc\(i\);
	    ptr[j] = j;
    	printf\("VALUE %d is:: %lu\\n",j,ptr[j]\);
    	brk\(ptr\+i\);
    	ptr1=\(ptr\+j\);
		printf\(" VALUE of trace end is::%lu\\n",ptr1\);
		i\+\+;
	\}
\}
return 0;

}

I was thinking of embedding time in such a way that I could track access to a particular growing memory size. The moment the access time varied, the cache level was changed. Am I thinking along the right lines, please guide me.

Interesting idea but your code seems to be too complicated for me.
Try to alloc memory once (e.g. 10MB)
and perform timing of 'mangling' areas of growing size:
256kB, 512kB, and so on.
Mangling can be as simple as mem[i]++

Regards