We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hi, I am using calloc in a function to allocate memory to my array. This function writes to the array different number of elements each time the function is called. Here is my problem. Say for the first time function writes to all the 3 locations and next time it writes to only first 2 locations. After the second call, the 3rd memory locations still contains the value written by the first function call. I understand that is the way it works.But I want to know if there is a way to erase all the locations before calling the function again? Is there any built-in function available? Also when I print the values of array initially it doesn't print zeroes. I have read that calloc initializes the memory fields to 0's. Following is the function code.
function write_to_array(int value) { int xdata *ascii_value,i; ascii_value = calloc(3, sizeof (int)); for(i=0;value!=0;i++) { mod = value%10; c = mod+'0'; ascii_value[i] = toascii(c); value/=10; } }
Hi Davis, I am using calloc to allocate memory, but it doesn't initialize the bytes to zero as it is expected to do. And I do not want to initialize the memory locations. I just want the locations to be cleared when the function is reentered. Thanks Ramya
I'm afraid I don't understand. What is the difference between "initialize the memory locations" (to zero) and "locations to be cleared"? To me, those mean the same thing, so I'd use memset() at the beginning of the function to clear the dynamically allocated array.
I am sorry Davis. I think I din't write it clearly. I said I do not want to initialize because you were talking about initializing the memory locations to something other than zeroes. If calloc is a combination of malloc and memset, it should initialize the locations to zero without me having to use the memset function. I was wondering why my code was printing some garbage values other than zeroes when I tried printing initial array. Thanks Ramya
I think you do not present the full problem (just a code sniplet where you think the problem might be). Take a look to the source code of calloc in the folder C:\keil\c51\lib\calloc.c