From: hansoft AT geocities DOT com (Hans Bezemer) Newsgroups: comp.os.msdos.djgpp Subject: Re: why does this work like this (char allocation question)?? Date: Thu, 14 Aug 1997 07:42:21 GMT Organization: HanSoft & Partners Lines: 64 Message-ID: <33f2b39a.1419316@news.nl.net> References: <33EC75ED DOT 2EA9 AT primenet DOT com> Reply-To: hansoft AT geocities DOT com NNTP-Posting-Host: utr97-1.utrecht.nl.net To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk On 13 Aug 1997 20:08:00 -0700, "Smith A. Cat" wrote: >when i run this: > >#include >char buffer[4]; >void main(void){ >printf("%s %d", gets(buffer), sizeof(buffer)); >} >for an input string up to about 64 characters (i'm not sure how many due >to impatience...) it echos the input string, and prints *4* for the >size. when the string gets longer, it segs out. Ok, I'll tell this only once. Once you define buffer [4], you allocate a fixed string of 4 bytes. Everything beyond that is not allocated by you and god knows whats there. gets() doesn't limit what length of string you put there. Once you call it, it gets the address of buffer along and starts writing from there. sizeof (buffer) is determined at compile time and is the static size of the variable, which in this case is 4 bytes. Whatever you store there is irrelevant. Try this: #include main() { char *buffer; char str [32] = "This is me"; buffer = str; printf ("%d, %d\n", sizeof (buffer), sizeof (str)); } This will print either "4, 32" or "2, 32" since the size of a pointer is 4 or 2 (depending on the compiler) and the sized string is always 32. What you probably meant was strlen(). BTW the nice thing of fgets() is that you can use sizof() with sized string arrays to limit the number of characters you input. Never do gets(). >why doesn't it seg out as soon as the string exceeds four characters?? Since you're still writing in a segment where you're allowed to write. Try this: #include char buffer[] = "four"; void main(void){ printf("%s %d", gets(buffer), sizeof(buffer)); } Some compilers will allocate that in a segment where you're not allowed to write. Others allow it or you can use a command line option to make it legal. Bad coding though! >the same thing happens if you declare the string as a pointer (*buffer). >does a declared variable name automagically get 64 bytes of exercise >space?? Doesn't care. You shouldn't write code like that. Try Visual Basic. Hans