When i run below code, I got realloc error and process got aborted. I am trying to understand memory reallocation by expanding size at every iteration. Somehow it got failed and clueless how to resolve this issue. Need help in proceeding further.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char **vector;
int num_entries;
} str_vector_t;
void frame_objs(str_vector_t *sv)
{
int max_objs = 5;
int i_idx = 0;
char path[40] = "Device.DeviceInfo.Process.";
char obj[45] = {0};
printf("sv:%p, sv->num_entries=%dn", sv, sv->num_entries);
sv->vector = calloc(max_objs, sizeof(char *));
sv->num_entries = max_objs;
for (i_idx = 0; i_idx < max_objs; i_idx++) {
memset(&obj, 0, sizeof(obj));
snprintf(obj, sizeof(obj), "%s%d", path, i_idx+1);
sv->vector[i_idx] = strdup(obj);
}
}
int main()
{
// Single pointer str vector as array
str_vector_t *sv = NULL;
int vendor_idx = 4;
int idx = 0;
//4 sets
for (idx = 0; idx < vendor_idx; idx++) {
sv = realloc(sv, idx+1 * sizeof(str_vector_t));
if (sv) {
memset(&sv[idx], 0, sizeof(str_vector_t));
printf("idx:%d, sv:%pn", idx, sv);
frame_objs(&sv[idx]);
}
}
return 0;
}
Output:
$ ./a.out
idx:0, sv:0x55e1b29b02a0
sv:0x55e1b29b02a0, sv->num_entries=0
idx:1, sv:0x55e1b29b02a0
sv:0x55e1b29b02b0, sv->num_entries=0
realloc(): invalid next size
Aborted (core dumped)
2