以编程方式堆栈或堆 [英] Stack or Heap programatically

查看:76
本文介绍了以编程方式堆栈或堆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何发现变量是在堆栈上还是以编程方式分配给堆?

如果是堆栈变量,则_CrtIsValidHeapPointer崩溃.

我想制作一个使用strcpy_s的方法/定义,但是使用sizeof()char *返回4,然后我使用_msize,当char cBuf [4]无效时,_msize不起作用...

像这样的东西:

How can I discover if a variable is on Stack or Heap allocated(programatically)?

_CrtIsValidHeapPointer crashes if is a stack variable.

I want to make a method/define to use strcpy_s, but with sizeof() char* returns 4, then i use _msize, whetever when char cBuf[4], _msize don''t work...

Something like this:

errno_t strcpyNew(char* c1, char* c2, int iSizeC1)
{
	if(iSizeC1 == 4 && _CrtIsValidHeapPointer((const void*)&c1))
		iSizeC1 = _msize(c1);

memset(c1,0,iSizeC1);

	if(iSizeC1 < strlen(c2))	
	{
		TRACE("ERROR.");
	}

	return strcpy_s(c1,iSizeC1,c2);
}

#define new_strcpy(c1, c2) strcpyNew(c1 , c2, sizeof(c1))



错误样本:



Error sample:

char cTeste4[4];

new_strcpy(cTeste4,"hi!");

推荐答案

要么正确更新代码,要么什么都不做.

strycpy_s已经正确实现.如果将strcpy替换为strcpy_s,则代码无法编译,则应手动对其进行修复.

任何其他选择都比什么都不做最糟糕.
Either properly update the code or do nothing at all.

strycpy_s is already properly implemented. If by replacing strcpy by strcpy_s, the code does not compile, you should fix it manually.

Any other alternative is worst than doing nothing at all.


在通话中
_CrtIsValidHeapPointer((const void*)&c1))


,您不会在调用中使用传递的指针,而是传递给函数的临时堆栈变量的地址.

请注意,在释放模式下,_CrtIsValidHeapPointer被存根.只能在调试中使用.


, you''re not using the passed pointer in the call, but instead the address of the temporary stack variable, passed to your function.

Note that in release mode _CrtIsValidHeapPointer is stubbed out. It only works in debug.


_CrtIsValidHeapPointer()崩溃,因为您传递了&c1.使用c1应该可以.请注意,仅对调试版本执行_CrtIsValidHeapPointer().

比较大小以独立于32/64位版本时,还应该使用sizeof(char *).
_CrtIsValidHeapPointer() crashes because you are passing &c1. Using c1 should work. Note that _CrtIsValidHeapPointer() is only executed for debug builds.

You should also use sizeof(char *) when comparing the size to be independent from 32/64 bit builds.


这篇关于以编程方式堆栈或堆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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