Hello,
for(i=0; i<1000; i++) QUEUEinit(50);
If I am correct in my thinking, you will have lost allocated memory in your program. Your pointer,q, is a variable. Allocating memory to it 1000 times will cause a problem.
According to the C89 Sec. 4.10.3: The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object and then used to access such an object in the space allocated (until the space is explicitly freed or reallocated).
Each time you call malloc, you request a block of freed space, if successful. You will have 1000 blocks of memory, as each time malloc is called, while q may point to only one, and the last, block of memory allocated.
According to the C89 Sec. 4.10.3: If the space cannot be allocated, a null pointer is returned. If the size of the space requested is zero, the behavior is implementation-defined; the value returned shall be either a null pointer or a unique pointer. The value of a pointer that refers to freed space is indeterminate.
Onto your next question.
What if, instead I had
Code:
for(i=0; i<1000; i++) {QUEUEinit(50); free(q); q=NULL;}
Does this mean that every time QUEUEinit() is called, the memory set aside for it will be freed before the next i, so I will never run out of memory?
I believe so. Each time QUEUEinit() is called, you request a block of memory. As in this loop, you free the memory block given toq each time, ensuring the memory allocated is de-allocated per loop increment:
According to the C89 Sec. 4.10.3: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs. Otherwise, if the argument does not match a pointer earlier returned by the calloc , malloc , or realloc function, or if the space has been deallocated by a call to free or realloc , the behavior is undefined.
- Stack Overflow