Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.
malloc (memory allocation) is used to dynamically allocate memory at run time. Possible uses for this function are:
Read records of an unknown length.
Read an unknown number of database records.
The simplest way to reserve memory is to code something like:
void main()
{
char string[1000];
strcpy (string, "Some text");
}
The example above has two problems:
If the data is less than 1000 bytes we are wasting memory.
If the data is greater than 1000 bytes the program is going to crash.
The 1000 bytes are reserved throught out the life of the program. If this was a long running program that rarely used the memory, it would again be wasteful.
malloc allows us to allocate exactly the correct amount of memory and with the use of free only for the time it is required.
Looking at the example syntax above, 1000 bytes are reserved and the pointer String points to the first byte. The 1000 bytes are NOT initialized by malloc. If the memory is NOT available, a NULL pointer is returned. Please note, the cast cast is required to return a pointer of the correct type.
Echo47 I think the use of strcpy() or strncpy() aren't the question, just idea of malloc use is important. About void main(), void main (void) depends of the compiler (some give an warning without void) and int main(void) is used generaly for C++ and some compilers introduce automatically int main(int argc,char*argv[]) on project. I think it isn't the problem too. About cast I removed it example of an book ... but I agree which desnecessary but I don't see problems of use, I think the autor use it for clean ....
Can you explain to me why void main() and cast can be unsafe?
i think there is no major diff btw ther two statements and i depends on the compiler..
when ever main() ,is written it is understood that there are no arguments and hence main(void) is unnecessary..
and void main() and int main(void) , here if you are using the second one
we need to mention the statement "return 0;" at the end of the program..
else there may be chance of returning someother integer.. so its better to use
void main() in all cases
regards
Oops, I didn't mean that it's wrong to cast malloc's return value. It is correct, but redundant: https://www.eskimo.com/~scs/C-faq/q7.7.html
Most programmers don't use it anymore because it just adds clutter.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.