This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char ipaddr[20];
char filename[2048];
}iplog;
int main(){
unsigned long numrec=0;
iplog* e=(iplog*)calloc(1,sizeof(iplog)+1);
iplog* p=e;
memcpy(e->ipaddr,"127.0.0.1",20);
memcpy(e->filename,"/bla/bla/bla",2048);
e=(iplog*)realloc(e,sizeof(iplog)*(numrec++)+1); //memory not growing?
e++;
memcpy(e->ipaddr,"192.168.1.2",20);
memcpy(e->filename,"/abc/def/ghi",2048);
for (*p;p;p++){
printf("IP=%s, File=%s\n",p->ipaddr,p->filename);
}
free(e);
return 0;
}
What I'm trying to do is create an array of structs in RAM. I can't use the format array[n].element=value
because I don't know how much memory I'll need to process all the elements so I figure reallocating the memory each time would be of benefit. When I do introduce realloc, segmentation faults happen.
Here's my logic and correct me where I make the mistake. First I allocate enough memory (via sizeof(iplog))
plus one byte for the null character. Then I send data to each element of the struct. No problems there.
I take the original allocated pointer for memory access to use inside realloc so I don't allocate hundreds of new blocks of memory chunks with their own pointers. the value of the second parameter is enough space to contain all the struct data I need. I used numrec++ to allow for this.
I then increment the data pointer ( via e++) to write data to the new space in memory.
Finally, I use the original pointer that I used to allocate memory for the first time with to try to iterate through the data in memory to print it and all I see for output is an incorrect number of lines printed along with segmentation fault as follows:
IP=, File=
IP=, File=
...
...
IP=, File=
IP=, File=
Segmentation fault
What I was expecting from the above code is this:
IP=127.0.0.1, File=/bla/bla/bla
IP=192.168.1.2, File=/abc/def/ghi
What am I doing wrong? I'm assuming it has to do with realloc?