L
Longfellow
I'm finally going to try to understand dynamic allocation of memory.
I've always just declared arrays (foo[xx]), but that's too limiting now.
I've looked at K&R2 (7.8.5 Storage Management: about 3/4 of a page, no
examples, just prototypes). D&D: half a page followed by some
warnings. C Traps and Pitfalls, and Expert C Programming: the standard
gotchas. And finally, comp.lang.c faq: a whole section on memory
allocation (7.x) with lots of wrong ways explained.
Nowhere that I can wrap my head around: clear examples of the Right Way
(tm). And, yes, I may well be in my *dense* period.
So this code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char *buffer;
if ((buffer = malloc(80)) == NULL) return 1;
printf("sizeof buffer is %d\n", sizeof buffer);
free(buffer);
return 0;
}
It compiles and runs:
sizeof buffer is 4
If I insert code to read from stdin (using fgets), printing the input to
the screen yields exactly three characters (three plus '\0', I presume).
OTOH, if I 's/char *buffer;/char buffer[80];/', and delete the 'if ((...'
and 'free(...' lines, I get "sizeof buffer is 80".
Obviously, I'm clueless here. Would someone point me to a venue where a
knowledgeable person would be more than willing to patiently explain
enough of what I don't know so that I can bootstrap my knowledge with
practice? I hesitate to ask that here, but would be delighted if
someone would offer same!
Thanks for reading,
Longfellow
I've always just declared arrays (foo[xx]), but that's too limiting now.
I've looked at K&R2 (7.8.5 Storage Management: about 3/4 of a page, no
examples, just prototypes). D&D: half a page followed by some
warnings. C Traps and Pitfalls, and Expert C Programming: the standard
gotchas. And finally, comp.lang.c faq: a whole section on memory
allocation (7.x) with lots of wrong ways explained.
Nowhere that I can wrap my head around: clear examples of the Right Way
(tm). And, yes, I may well be in my *dense* period.
So this code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char *buffer;
if ((buffer = malloc(80)) == NULL) return 1;
printf("sizeof buffer is %d\n", sizeof buffer);
free(buffer);
return 0;
}
It compiles and runs:
sizeof buffer is 4
If I insert code to read from stdin (using fgets), printing the input to
the screen yields exactly three characters (three plus '\0', I presume).
OTOH, if I 's/char *buffer;/char buffer[80];/', and delete the 'if ((...'
and 'free(...' lines, I get "sizeof buffer is 80".
Obviously, I'm clueless here. Would someone point me to a venue where a
knowledgeable person would be more than willing to patiently explain
enough of what I don't know so that I can bootstrap my knowledge with
practice? I hesitate to ask that here, but would be delighted if
someone would offer same!
Thanks for reading,
Longfellow