FYI:
1. malloc() returns a void pointer and there is absolutely nothing wrong
with using a type cast on the return value. In case you did not know,
stdlib.h has nothing to do with casting. Whether you decide to cast or not
any decent compiler will generate a warning and assume a return value of int
for malloc() if stdlib.h is not included.
2. By definition sizeof(char) maybe 1 in your machine. Not mine. So make
sure to use sizeof(char) to be portable.
Finally, whoever told you that void main(void) is not valid C? I recommend
you get a copy of K&R and read it.
ipo
43:52 GMT, "ipo"]
wrote in comp.lang.c:
****DON'T TOP POST. New material you add belongs after quoted
material you are referring to. If you want to use Microsoft's
brain-dead virus spreading and posting software (free, and not worth
its price), then YOU need to make the extra effort to put the cursor
where it belongs before you start typing.
The memory of mystring is not freed by this code since the function returns
prior to reaching free(mystring). Whether you will run into memory leaks
depends on whether the memory is freed elsewhere in the program. Don't
confuse the scope of the local variable mystring with the scope of the thing
it points to. Your code should read as follows:
NO IT SHOULD NOT READ AS FOLLOWS. Your example contains examples of
both poor C programming practice and undefined behavior.
char *getString(void) {
char *mystring;
mystring = (char *) malloc(80* sizeof(char));
Poor practices:
1. NEVER cast the pointer returned by malloc() in C. It is not
necessary if <stdlib.h> has been included, and can hide a valuable
warning if <stdlib.h> has not been included.
2. By definition, sizeof(char) in C is 1. It always has been, and
always will be. Multiplying by sizeof(char) is always unnecessary and
obfuscating.
Instead code the line above:
mystring = malloc(80 * sizeof *mystring);
Now the code is bullet-proof, even if you change the type of mystring
to be a pointer to something else larger than 1 byte.
And now your compiler is required to issue a diagnostic if you did not
return(mystring);
}
void main(void) {
Apparently you are talking about some language other than C, no matter
how much it looks like C. I understand that "void main()" is correct
Java, for example, but it is not legal C. main() returns an int in C.
char *myName;
myName = getString();
if (myName != NULL) {
strcpy(myName, "Bill Clinton");
printf("%s\n", myName);
free(myName);
}
}
When getString() returns, mystring goes out of scope. But note that what the
function returns is a pointer to a 80-character memory chunk. After that
note that I make sure that main() calls free() to release the memory chunk
once I'm done with it.
I hope this helps
ipo
--
Jack Klein
Home:
http://JK-Technology.Com
FAQs for
comp.lang.c
http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++
http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq[/QUOTE]