如果在同一指针(C)上两次使用malloc,会发生什么情况? [英] What happens if I use malloc twice on the same pointer (C)?

查看:1348
本文介绍了如果在同一指针(C)上两次使用malloc,会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我创建了一个指针newPtr,并使用了malloc(一些大小),然后稍后又使用了相同的指针再次使用了malloc(一些大小).怎么了?然后,我是否要创建第二个内存块,其大小与第一个相同? newPtr指向相同的地址吗?

Say for instance I created a pointer newPtr and I use malloc(some size) and then later I use malloc(some size) again with the same pointer. What happens? Am i then creating a second block of memory the same size of the first one? Does newPtr point to the same address?

示例:

int *newPtr;
newPtr = malloc(10 * sizeof(int));
newPtr = malloc(10 * sizeof(int));

推荐答案

您的程序将发生内存泄漏. newPtr的第一个值将丢失,并且您将无法free.

Your program will have a memory leak. The first value of newPtr will be lost and you will not be able to free it.

然后我要创建第二个与第一块相同大小的内存吗?

Am i then creating a second block of memory the same size of the first one?

是的.您正在分配与第一个对象不同的第二个对象.

Yes. You are allocating a second object, distinct from the first one.

newPtr是否指向相同的地址?

Does newPtr point to the same address?

不.这些对象是不同的,因此它们的地址是不同的.

No. The objects are distinct, so their address are distinct.

这篇关于如果在同一指针(C)上两次使用malloc,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆