将指向堆栈变量的指针传递给realloc()是否有效? [英] Is it valid to pass a pointer to a stack variable to realloc()?

查看:71
本文介绍了将指向堆栈变量的指针传递给realloc()是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
   char myString = NULL;
   realloc(&myString, 5);
   strncpy((char *)&myString, "test", 5);
}

似乎可以正常工作,但是我对堆栈还是堆还是有些困惑.可以吗?如果允许,myString是否需要手动释放,还是在超出范围时将其释放?

Seems to work fine but I'm still slightly confused about stack vs heap. Is this allowed? If it is allowed, does myString need to be freed manually or will it be released when it goes out of scope?

感谢您的答复,所以我认为这同样是非法的

Thanks for the responses, so i presume this is equally illegal

//I want the code to change myString to "tests"
char myString[5] = "test";
realloc(&myString, strlen(myString)+2);
myString[4] = 's';
myString[5] = '\0';

推荐答案

不,这是完全错误的. realloc只能用于重新分配malloc分配的内存,您所做的只是偶然的,最终会崩溃

No, this is completely wrong. realloc should only be used to reallocate memory allocated by malloc, what you are doing works only by accident, and will eventually crash horribly

char *myString = malloc(x);
myString = realloc(myString,y);
free(myString)

但是,最好使用new和delete,甚至最好使用std :: string.

You are better off using new and delete, and even better off using std::string, however.

这篇关于将指向堆栈变量的指针传递给realloc()是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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