![]() |
|
|
|
|
|||||||
| Forums | Portal | Register | Forum Rules | FAQ | Contribute | Members List | Arcade | Search | Today's Posts | Mark Forums Read |
| UNIX for Advanced & Expert Users Advanced UNIX and Linux questions go here. Expert-to-Expert. |
|
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| questions in memset | arunkumar_mca | UNIX for Dummies Questions & Answers | 7 | 08-09-2007 09:08 AM |
| about memset fuction | ranj@chn | High Level Programming | 3 | 01-31-2006 05:59 AM |
|
|
Submit Tools | LinkBack | Thread Tools | Display Modes |
|
#1
|
|||
|
|||
|
memset vs calloc
Dear Friends,
Can any one tell me the difference between memset and calloc function in C. Regards, Selvi |
| Forum Sponsor | ||
|
|
|
#2
|
|||
|
|||
|
Uh oh... best being moved/posted in High level programming subforum next door I guess (if no answer comes).
|
|
#3
|
|||
|
|||
|
memset() initializes byte strings to a user supplied value that is restricted to the unsigned char range. It does not allocate any memory.
calloc() allocates memory of any type (char, int, struct) and initializes that storage to zeros. Both initialize a given storage area [memset() being the more exclusive of the two functions] but only one allocates memory for storage of a particular object type. |
|
#4
|
|||
|
|||
|
calloc() is usually used to create arrays. It's sort of like malloc() in that it allocates memory, but calloc() as shamrock points out sets the allocated memory to 0.
The effect of calloc() is the same as doing malloc() followed by memset(). |
|
#5
|
|||
|
|||
|
Dear Friends,
Thank you for your reply. Actually when I was reading the code of the traceroute I saw the following statement. outip = (struct ip *)malloc((unsigned)packlen); if (outip == NULL) { Fprintf(stderr, "%s: malloc: %s\n", prog, strerror(errno)); exit(1); } memset((char *)outip, 0, packlen); outip is of datatype struct ip *. packlen is the size of the packet (i.e, 40 bytes). My doubt is why here they not using the calloc function. Regards, Selvi. |
|
#6
|
|||
|
|||
|
That is older C code (because modern malloc does not anbd should be cast).
I'm guessing: Some older calloc implementations had problems actually zeroing out the allocated memory. So maybe the coder knew this was a problem. Plus, calloc does call an equivalent of memset anyway - so it is up to you to choose which one to use: malloc + memset or calloc. I personally seldom use calloc. |
|
#7
|
|||
|
|||
|
The reason is that calloc() implies array access. They are not treating the memory area as an array here so use malloc(). calloc() is rarely used it seems to me, and in this case would not make any sense to use. Think about it, what would you make an array of in this case, what type?
|
|||
| Google The UNIX and Linux Forums |