[OCLUG-devel] malloc() woes

Dan Stromberg strombrg at dcs.nac.uci.edu
Sun May 29 12:47:39 PDT 2005


You'll probably want to declare your initial "buffer" as a char *, and
then get some memory for it via malloc(), when you first need to use it.

Then if/when you're ready to change the amount of memory pointed to by
buffer, you'll probably want to use realloc().

On Sun, 2005-05-29 at 12:06 -0700, James Colannino wrote:
> I hope my frequent questions on the list don't start to annoy anyone. 
> I'm having some trouble figuring out how to expand a variable's size if
> it's not big enough.  I've already written the code, and so far, most of
> what I've written doesn't cause the compiler to spit out any errors
> (although I'll probably have some bugs the first time I run it.) 
> There's one thing that I can't get around though.  Here's a snippet of
> code to illustrate what I'm doing:
> 
> char buffer[BUFFER_SIZE];
> /* BUFFER_SIZE is a constant - it's currently set to 80 */
> 
> char *buffer2;
> /* this is used as temporary storage for a new pointer */
> 
> fgets (buffer, sizeof(buffer), file);
> /* for the sake of brevity, the code dealing with file is not here */
> 
> if (buffer[BUFFER_SIZE] != '\n') {
>     buffer2 = more_memory(buffer);
> 
> /* the function more_memory() returns a pointer to new memory if it was
> successful and the old pointer if it was not.  After this function is
> called, I do some checking to make sure buffer2 != buffer (which would
> mean that it just returned the same pointer, and thus,  there isn't
> enough memory) then I try to do the following: */
> 
> buffer = buffer2;
> 
> This results in the following compiler error:
> 
> "incompatible types in assignment"
> 
> I tried different variations that I knew would probably also fail such as:
> 
> buffer = (char *)buffer2;
> &buffer[0] = (char *)buffer2;
> 
> I of course didn't expect those to work, but it was a vain attempt to
> try and figure out why I can't do this.  I slowly realized that while
> typing buffer by itself does denote a pointer to the string, the
> variable buffer isn't directly declared as a pointer but rather as an
> array, so I'm guessing that since buffer2 is a pointer and buffer is a
> character array, that's where my problem is.  But now I can't figure out
> how to get buffer to point to the new block of memory :(
> 
> Any ideas?  Thanks in advance :)
> 
> James
> 
> P.S. If I get annoying just let me know ;)
> 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
Url : http://localhost.localdomain/pipermail/oclug-devel/attachments/20050529/c74e5724/attachment.bin 


More information about the OCLUG-devel mailing list