I'm trying to allocate a block of memory and then copy data into that space. I made this simple program and it doesn't do what I expect it to do. Could someone please point out my faulty reasoning.
Thanks.
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
int t1 = 11;
int t2 = 22;
int *bufptr;
bufptr = calloc(2, sizeof(int));
if(bufptr == NULL)
{
fprintf(stderr, "Out of memory, exiting\n");
exit(1);
}
memcpy(bufptr, &t1, sizeof(int));
memcpy((bufptr+sizeof(int)), &t2, sizeof(int));
printf("bufptr11: %d\n", *bufptr);
printf("bufptr22: %d\n", *bufptr+sizeof(int));
}
What it prints out is the following:
bufptr11: 11
bufptr22: 15 (this should be 22 and not 15)
Thanks for all the help everybody, but I just ran into my next snag! The whole point of this exercise is to send some data via udp to another host. I look at the content of the bufptr before I call sendto(), everything looks fine and the sending seems to go well. On the other side (I'm running client/server on 127.0.0.1) I just receive "crap". I call recvfrom(s_fd, bufptr, buflen, etc). I use the same calloc call for allocating memory for bufptr. There is the right amount of data being returned from this call, but the content of it is all just rubbish!
bufptr = calloc(2, sizeof(int));
if(bufptr == NULL)
{
fprintf(stderr, "Out of memory, exiting\n");
exit(1);
}
buflen = 2*sizeof(int);
rc = recvfrom(sd, bufptr, buflen, 0, (struct sockaddr *)&serveraddr, &serveraddrlen);
printf("t2: %d\n", *bufptr);
printf("t3: %d\n", *(bufptr+1));