HP OpenVMS Systems

ask the wizard
Content starts here

C programming and memory (re)allocation?

» close window

The Question is:

 
I'm trying to correct a bug in a c program using
DEC C V5.7-004 on OpenVMS Alpha V7.1 involving the use of the realloc function.
 
In short, the program builds a string by appending substrings.  The following
 sample, "aaabbbcccdddeeefff",  might show appending 5 segments to the initial
 string, "aaa" with 5 successive calls to realloc in a loop.
 
My symptom is that my string looses  middle
segments and might appear as "aaaeeefff".
                                 ^stuff missing
 
I can see the accumulator string build up with segments, like "aaabbbcccddd",
 then, after a call which relocates the object to a new address of new block,
 it looses content in its middle to become "aaaeeefff".
 
The function may be invoked as follows:
char *block_of_new_size ;
char *old_block ;
size_t size_of_new_block;
...
<initial heap block loaded with "aaa">
...
<loop>
...
block_of_new_size = (char *)realloc((void *)old_block, size_of_new_block);
...
strcat( block_of_new_size, next_segment ); /*new_segment contains "bbb" or
 "ccc", etc. with successive passes of the loop */
<end_loop>
...
I'm exploring whether I give a value of "size_of_new_block" which is too small
 and
causes realloc to transfer too few characters from the old block to the new
 one...  This may explain the bug...
 
But I was also wondering how dec c keeps track of the sizes of the blocks of
 heap memory issued by realloc?  Is the size stored with the block so that I
 might overwrite it accidentally and corrupt it in such a fashion to confuse
 realloc about how large th
e old block is at a particular address might be?
 
Are there any known bugs or restrictions associated with realloc?
 


The Answer is :

 
  The OpenVMS Wizard prefers to use the lib$vm services directly, as
  these can be tailored to the particular needs of the application.
 
  Please be aware that strcat will look for a null byte, and will
  continue to traverse memory until one is located.  The requested
  string concantenation operation will then ensue.  This null byte
  must obviously be accounted for and be present within the storage
  allocated for the structure, or various corruptions can arise.
 
  When posting such questions, a complete reproducer is appreciated and
  greatly simplifies providing an answer -- open-ended "are there any
  bugs?" questions are exceedingly difficult for the OpenVMS Wizard to
  answer (in any specific terms).
 
  Does your loop update the variable "old block"?  If not, then each
  realloc may create a new block initialized with just the (current)
  contents of the first block of memory passed in...
 

answer written or last revised on ( 18-OCT-2000 )

» close window