Tim Pungračič Tim Pungračič - 1 year ago 98
C Question

C counting allocated memory

I have to make a program that would allocate an array of

and then count how much memory was actually allocated to it.

So far I have the code that allocates the array, but I don't know how to count the allocated memory. This is what I tried so far:

the handler:

int i;
void segfault_sigaction(int signal, siginfo_t *si, void *arg)
printf("ujel segafult, velikost pomnilnika je: %d bajtov\n", sizeof(int) * i);


int main(int argc, char* argv[])
int *addr;
int n = atoi(argv[1]);
struct sigaction sa;

sa.sa_handler = segfault_sigaction;
//sa.sa_sigaction = segfault_sigaction;
//sa.sa_flags = 0;

sigaction(SIGSEGV,&sa, NULL);

addr = mmap(NULL, n * sizeof(int), PROT_WRITE | PROT_READ ,MAP_ANONYMOUS | MAP_PRIVATE,-1,0);
i = n;


addr[i+1] = 5;
return 0;

EDIT: after reading your answers and the task description again I changed the code, I put in a handler that catches SEGFAULT, but it is not really reliable(sometimes it works, sometimes the default segmentation fault error occurs).

Answer Source

The amount of memory mapped by mmap() is just what you requested, perhaps rounded up a bit. If you're asking, "How can I see how much it rounded up," the answer is you can't do so in a general way, but some specific platforms may have APIs that let you figure it out. But there's no reason why you'd need to.

The code you've written seems to be "searching" for the end of the allocation by looking for a nonzero part. This results in undefined behavior because you will always run off the end of the allocation. You absolutely must not do this. Just use the size that you passed to mmap() as the size. That's the only size that matters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download