few errors with malloc,arguments,memory leak etc
#include<stdio.h>
#include<stdlib.h>
#define LOOPS 10开发者_如何学编程0
#define RAYSIZE 1024
int main (int argc, char **argv)
{
int count = 0;
char *pointer = NULL;
for(count=0; count<LOOPS; count++) {
pointer = (char *)malloc(sizeof(char) * RAYSIZE);
}
free(pointer);
return count;
}
You are leaking memory for first 99 times, as your free call is outside of loop. Only the last allocated memory is freed.
Each time through the loop you allocation some memory and set pointer
to point to it. When you do that pointer
is no longer pointing to the last piece of memory, but it's still allocated to your program. When you call free(pointer)
you're only freeing the last block of memory you allocated.
You should have as many calls to malloc
as to free
. Here you call malloc
in a loop, which mean that you will have many more calls to it than to free
.
精彩评论