Note that there are some explanatory texts on larger screens.

plurals
  1. POcalloc and copying data into memory area using c
    primarykey
    data
    text
    <p>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.</p> <p>Thanks.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; 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, &amp;t1, sizeof(int)); memcpy((bufptr+sizeof(int)), &amp;t2, sizeof(int)); printf("bufptr11: %d\n", *bufptr); printf("bufptr22: %d\n", *bufptr+sizeof(int)); } </code></pre> <p>What it prints out is the following:<br> bufptr11: 11<br> bufptr22: 15 (this should be 22 and not 15)</p> <p>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! </p> <pre><code>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 *)&amp;serveraddr, &amp;serveraddrlen); printf("t2: %d\n", *bufptr); printf("t3: %d\n", *(bufptr+1)); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload