gordonb.z2prq
8/11/2011 10:01:00 AM
> I have been looking for a function from ANSI C that would start out with
> a buffer size of zero initialized and would grow to a certain size. I have
A buffer is not of size zero. C doesn't have zero-sized objects.
Even if it did, you can't initialize a zero-sized buffer without
overflowing it.
> already been able to set aside a 32 byte type using malloc(). Could calloc()
You can use realloc() to change the size of a malloc()ed buffer
(upwards or downwards). You can use memset() to clear, for example,
the newly-allocated part of the buffer (assuming the size grew).
Or, your code can fill in the appropriate values.
Beware that memset() is not appropriate to initialize struct elements
that are pointers or floating-point types (if that's what you are
going to put in the buffer) where all-bits-zero doesn't guarantee
a specific value. A NULL pointer is not guaranteed to be represented
as the bit pattern 0xdeadbeef even on machines where pointers are
32-bits.
> be what I'm looking for? This buffer would be able to grow by a mechanism
> that would include using fscanf to find the size of a file in bytes. So my
By the time you have found out the size of a file in bytes, the size
of that file might have already changed. If you take one pass through
the file to calculate its size, allocate that much memory, and then read
the file again, you might end up overflowing the file or losing the last
part of it if it grows between passes.
You can allocate an initial buffer, and keep growing the buffer
(usually *NOT* by one byte at a time; this is horribly inefficient)
with realloc() as needed until you've read the whole file. Some
people like doubling the size of the buffer each time. Then,
perhaps, you can shrink the buffer down to the actual size used.
The file still might grow while or after you finish reading it.
> question is simply is there any functions or ways in c89 to fill a buffer to
> a certain size before it's clear?
Filling a buffer does not change its size (unless you specifically
code a call to realloc() in this situation). Changing the size of
a buffer with realloc() does not "clear" it - the data in the minimum
size of the buffer before and after the realloc() is preserved.
This question does not make any sense. Please define the word
"clear" as you use it here. I don't think that "filled with zero
bytes" nor "transparent; lacking color and colour" makes sense here.
Neither is the question "clear".
> int buffer[] won't work unless it's a
> char.
int buffer[] as a definition won't work even if <it> is a char,
regardless of what <it> refers to. You have to specify a (nonzero) size.