请问如下代码有无内存泄漏?为什么?
请问如下代码有没有内存泄漏?其中的str1,str2占用的内存,最终有没有被垃圾回收掉?为什么?我要求比较有理由的,比较有说服力的,比较权威的答案。
static void SearchRecord()
{
int id;
Console.WriteLine( "\nPlease enter the record id to be searched: ");
try
{
id = Convert.ToInt32(Console.ReadLine());
}
catch
{
id = -1;
}
Console.WriteLine( "Your input id is {0}. ", id.ToString());
string str1 = new string( '0 ', 1024);
string str2 = new string( '0 ', 1024);
TB001 tb = new TB001();
unsafe
{
fixed (byte* pstr1 = &(Encoding.ASCII.GetBytes(str1)[0]), pstr2 = &(Encoding.ASCII.GetBytes(str2)[0]))
{
int nRet = tb.SearchRecord(id, (sbyte*)pstr1, (sbyte*)pstr2);
switch (nRet)
{
case 0:
Console.WriteLine( "Record found, {0}, {1}, {2}.\n ", id.ToString(), pstr1-> ToString(), pstr2-> ToString() );
break;
case -1:
Console.WriteLine( "Record with id = {0} not found.\n ", id.ToString() );
break;
}
}
}
}
[解决办法]
内存泄露在C++里面是发生在自己new了内存,但是忘了delete.
在C#里面是使用了非托管资源,忘了Close, 或者存在环引用.
你的例子明显不存在上面任何一种情况.