当前位置:  开发笔记 > 运维 > 正文

calloc并使用c将数据复制到内存区域

如何解决《calloc并使用c将数据复制到内存区域》经验,为你挑选了1个好方法。

我正在尝试分配一块内存,然后将数据复制到该空间.我制作了这个简单的程序,并没有按照我的预期去做.有人可以指出我错误的推理.

谢谢.

#include 
#include 

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));
}

打印出的内容如下:
bufptr11:11
bufptr22:15(这应该是22而不是15)

感谢所有人的帮助,但我刚刚陷入了下一个障碍!本练习的重点是通过udp将一些数据发送给另一台主机.在调用sendto()之前我查看了bufptr的内容,一切看起来都很好,发送似乎进展顺利.另一方面(我在127.0.0.1上运行客户端/服务器)我只收到"废话".我叫recvfrom(s_fd,bufptr,buflen等).我使用相同的calloc调用为bufptr分配内存.从这次调用中返回了适量的数据,但它的内容都只是垃圾!

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));

Matthew Flas.. 5

printf("bufptr22:%d \n",*(bufptr + sizeof(int)));

编辑:比parens更加阴险的事实(我一开始很想念),你实际上是在过度指针运算.编译器已经将bufptr + x调整为bufptr +(x*sizeof(int))字节.所以,当你这样做bufptr + sizeof(int)时,实际上是超出了分配的内存.

你可以看到这个:

printf("bufptr: %p\n", bufptr);
printf("bufptr + sizeof(int): %p\n", bufptr + sizeof(int));

例如,我(32位机器)它输出:

bufptr: 0x876f008
bufptr + sizeof(int): 0x876f018

相隔 16个字节,当我只分配了8个!提醒比bufptr[1]看起来更有用.

这是一种通常最初不会显示的可怕错误,然后在修改不相关的代码时开始导致崩溃. valgrind会抓住它.



1> Matthew Flas..:

printf("bufptr22:%d \n",*(bufptr + sizeof(int)));

编辑:比parens更加阴险的事实(我一开始很想念),你实际上是在过度指针运算.编译器已经将bufptr + x调整为bufptr +(x*sizeof(int))字节.所以,当你这样做bufptr + sizeof(int)时,实际上是超出了分配的内存.

你可以看到这个:

printf("bufptr: %p\n", bufptr);
printf("bufptr + sizeof(int): %p\n", bufptr + sizeof(int));

例如,我(32位机器)它输出:

bufptr: 0x876f008
bufptr + sizeof(int): 0x876f018

相隔 16个字节,当我只分配了8个!提醒比bufptr[1]看起来更有用.

这是一种通常最初不会显示的可怕错误,然后在修改不相关的代码时开始导致崩溃. valgrind会抓住它.

推荐阅读
N个小灰流_701
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有