2011-03-23 2 views
0

좋은 아침, 오후 또는 밤,안전 인덱싱 내부 안전하지 않은 코드

서문 : 아래 코드는 아무것도 정말 유용하지 않습니다. 단지 설명을위한 것입니다.

안전하지 않은 코드에 배열 "안전 모드"를 할당하고 사용하는 데 문제가 있습니까? 예를 들어, 나는

public static unsafe uint[] Test (uint[] firstParam, uint[] secondParam) 
{ 
    fixed (uint * first = firstParam, second = secondParam) 
    { 
     uint[] Result = new uint[firstParam.Length + secondParam.Length]; 

     for (int IndTmp = 0; IndTmp < firstParam.Length; Result[IndTmp] = *(first + IndTmp++)); 
     for (int IndTmp = 0; IndTmp < secondParam.Length; Result[IndTmp + firstParam.Length] = *(second + IndTmp++); 

     return Result; 
    } 
} 

로 내 코드를 작성해야하거나 내가 대신 매개 변수로 포인터 만하고 길이를 받아들이는 별도의 안전하지 않은 방법을 작성하고 주요 기능에 사용해야합니까? 또한

, 내가 포인터로 Result을 사용하고 여전히 uint[]Result를 반환 할 수있을 수 있도록 내가

uint * Result = stackalloc uint[firstParam.Length + secondParam.Length] 

으로 할당을 대체 할 수있는 방법은 무엇입니까?

대단히 감사합니다.

답변

2

속도에 대한 포인터를 사용하는 경우에도 Result에도 포인터를 사용하는 것이 좋습니다. 아마 다음과 같이 :

public static unsafe uint[] Test (uint[] firstParam, uint[] secondParam) 
{ 
    uint[] Result = new uint[firstParam.Length + secondParam.Length]; 
    fixed (uint * first = firstParam, second = secondParam, res = Result) 
    { 
     for (int IndTmp = 0; IndTmp < firstParam.Length; IndTmp++) 
      *(res + IndTmp) = *(first + IndTmp); 
     res += firstParam.Length; 
     for (int IndTmp = 0; IndTmp < secondParam.Length; IndTmp++) 
      *(res + IndTmp) = *(second + IndTmp++); 
    } 
    return Result; 
} 

반환 아무것도 당신에게 stackalloc하지 마십시오! 함수가 반환되면 스택에 할당 된 영역이 다시 사용되어 잘못된 포인터를 제공합니다.