01-23-04 10:36 PM
Hello, I'm having a problem with malloc, memcpy and a struct that I just
can not figure out. This sort of simulates an STL vector push_back(), in
that it is a block of memory that grows as I add structs to it. I malloc
memory for the size of the records currently stored plus one (more
struct), copy the old data to the new memory area, then append the new
data into the remaining space. Afterwards, I run through the memory and
dump some data. The output I expect is this:
0: filler
1: fake num 1
2: fake num 2
3: fake num 3
However, the output I'm getting is this:
0: filler
1:
2:
3: fake num 3
It seems like not all of previous data is copied properly, though I can
not locate the problem. Could perhaps someone shed some insight into
this? Am I going about what I want to do wrong? I would really
appreciate any ideas.
/* note, most of this code is taken out of my larger program */
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <sys/socket.h>
#define ITERN 3
#define IW_ESSID_MAX_SIZE 32
struct mystruct
{
int mode;
struct sockaddr addr;
int qual;
int max_qual;
float freq;
char essid[IW_ESSID_MAX_SIZE + 1];
char key[27];
};
int main(int argc, char *argv[])
{
int n;
struct mystruct s;
int *ptr, *tptr;
strcpy(s.essid, "filler");
for (n = 0; n < 1 + ITERN; n++)
{
if (n == 0)
{
ptr = malloc(sizeof(struct mystruct));
if (ptr == NULL)
err(EXIT_FAILURE, "malloc()");
memcpy(ptr, &s, sizeof(struct mystruct));
}
else
{
sprintf(s.essid, "fake num %d", n);
/* get room for previous records, plus this new one */
tptr = malloc(sizeof(struct mystruct) * (n + 1));
if (tptr == NULL)
err(EXIT_FAILURE, "malloc()");
/* copy the previous records and free */
memcpy(tptr,
ptr,
sizeof(struct mystruct) * n);
free(ptr);
/* append the new record and save the pointer */
memcpy(tptr + (sizeof(struct mystruct) * n),
&s,
sizeof(struct mystruct));
ptr = tptr;
}
}
for (n = 0; n < 1 + ITERN; n++)
{
memcpy(&s,
ptr + (sizeof(struct mystruct) * n),
sizeof(struct mystruct));
printf("%d: %s\n", n, s.essid);
}
free(ptr);
return 0;
}
--
Eric Enright /"\
sauronAtiptsoftDcom \ / ASCII Ribbon Campaign
X Against HTML E-Mail
Public Key: 0xBEDF636F / \
[ Post a follow-up to this message ]
|