In C can you have realloc inside realloc? For example, a struct inside a struct when you need to malloc both of them and realloc both of them. If yes can someone please provide a simple example? Thank you in advance.
1 Answers
Your question is not dreadfully clear, but...
Yes, a given dynamically allocated structure (for example, an array of structures) can itself contain pointers to allocated data (such as various other arrays of allocated structures), and you can reallocate the various parts independently.
However, the system will not call realloc()
for you while you are reallocating one of the structures; you would have to separately program the various resizing operations.
Example nested data structures:
struct line { char *info; size_t length; };
struct section { size_t num_lines; struct line *lines; };
You could allocate an array of sections, and reallocate that array when needed. Each section contains an array of lines, and each of those arrays of lines can be independently reallocated too.
Hence:
size_t num_sections = 0;
size_t max_sections = 0;
struct section *sections = 0;
if (num_sections == max_sections)
{
size_t new_max = (max_sections + 1) * 2;
struct section *new_sections;
if (sections == 0)
new_sections = malloc(new_max * sizeof(*new_sections));
else
new_sections = realloc(sections, new_max * sizeof(*new_sections));
if (new_sections == 0)
...out of memory error...
sections = new_sections;
max_sections = new_max;
}
struct section *section = §ions[num_sections++]; // Newly available section
section->num_lines = 0;
section->lines = 0;
return section;
(I'm assuming C99 - with variable declarations where I want them.)
A similar process applies for the array of lines within a section, except the section structure doesn't have separate values for the number of allocated lines and the number of lines actually in use. Each line also has its own allocated memory for the string of characters, of course...

- 730,956
- 141
- 904
- 1,278
-
So you are not reallocing section, but you are reallocing sections? So I am wondering if instead of – Paul Kar. Nov 15 '10 at 05:38
-
struct section *section = §ions[num_sections++]; can you do another realloc? Assuming you have malloc on that as well. – Paul Kar. Nov 15 '10 at 05:39
-
@Paul Kar: yes, I could increment the count of the number of sections one at a time, but there is some cost to reallocating data, so you normally increment the number of entries by more than one at a time. I chose, quasi-randomly, to use (N+1)*2 for N = 0,1,2... (so 2, 6, 14, 30, ...) rows at a time. But the variations are legion. There are some subtle points in the code - like I use malloc() then realloc() but I could use just 'realloc()', and I carefully ensure that the original pointer is not damaged if the realloc fails. – Jonathan Leffler Nov 15 '10 at 05:50