如果我在分配指针之前不释放它会发生什么
我正在制作一个像这样的自定义复制函数:
if (s1 == NULL || s2 == NULL || s2->buf == NULL)
return;
if (s1->len + 1 < s2->len + 1)
{
if (s1->buf)
free (s1->buf);
s1->buf = (char *) malloc (s2->len + 1);
if (s1->buf == NULL)
return;
}
for (int i = 0; i < s2->len; i++)
s1->buf[i] = s2->buf[i];
s1->len = s2->len;
其中 s1 和 s2 只是结构指针,其中有一个 char 指针和一个无符号整数。
if (s1->len + 1 < s2->len + 1)
{
if (s1->buf)
free (s1->buf);
s1->buf = (char *) malloc (s2->len + 1);
if (s1->buf == NULL)
return;
}
这将检查 s1 内部是否有足够的空间来容纳 s2。如果没有,它将检查现有内存并释放它。完成后,它会为s1分配一个新的内存块,其大小为s2 + 1(包括\0)。
这就是我感到困惑的地方
如果 s2 的 char 指针中有足够的空间可以容纳 s1 (包括 \0),并且它不会 free() 并再次调用 malloc() ,它只是用for循环赋值,会保留s1原来的内容吗?
i am making a custom copy function like this:
if (s1 == NULL || s2 == NULL || s2->buf == NULL)
return;
if (s1->len + 1 < s2->len + 1)
{
if (s1->buf)
free (s1->buf);
s1->buf = (char *) malloc (s2->len + 1);
if (s1->buf == NULL)
return;
}
for (int i = 0; i < s2->len; i++)
s1->buf[i] = s2->buf[i];
s1->len = s2->len;
where as s1 and s2 are simply struct pointers that have a char pointer and an unsigned integer in them.
if (s1->len + 1 < s2->len + 1)
{
if (s1->buf)
free (s1->buf);
s1->buf = (char *) malloc (s2->len + 1);
if (s1->buf == NULL)
return;
}
this will check to see if there is enough space inside of the s1 to fit for s2. if there isn't, it will then check for existing memory and free it. after that is done, it will allocate a new memory block for s1, which is the size of s2 + 1 (include \0).
here is where i am confused
if there is enough space in the char pointer for s2 to fit into s1 (including \0) and it doesn't free() and call malloc() again, it just assigns with the for loop, will it keep the original contents of s1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果有足够的空间,则无需再次释放或分配。只需保留分配的块即可。
调用
malloc
并不是什么特别的事情:它只是为您提供一个可以开始存储数据的指针。如果您已经有了该指针,那就太好了。If there is enough space you don't need to free or malloc again. Just hold on to the allocated chunk.
Calling
malloc
isn't something special: it simply gives you a pointer where you can start storing data. If you already have that pointer, great.