CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    Jul 2009
    Location
    India
    Posts
    835

    [RESOLVED] _stprintf_s - Out of bound access

    Code:
      WORD iDay;
      TCHAR text[3];
       _stprintf_s(text, sizeof(text), _T("%d"), iDay);
    The above piece of code giving some out of bound access error by some Static code analyser. The iDay is used for Date: ie: 1 - 31.

    What should be the proper check to avoid this instead of using a CString in place or TCHAR. ?
    ◄◄ hypheni ►►

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: _stprintf_s - Out of bound access

    1. It should be _countof(text) instead of sizeof(text).
    From MSDN:
    sizeOfBuffer
    Maximum number of characters to store.
    2. WORD means unsigned short and its max value is 65535 which requires at least 6-character buffer for formatting (5 for digits + 1 for terminating NULL)
    Victor Nijegorodov

  3. #3
    Join Date
    Jul 2009
    Location
    India
    Posts
    835

    Re: _stprintf_s - Out of bound access

    Another quick solution would be

    Code:
    WORD iDay;
      TCHAR text[3];
      if(iDay <= 31)
        _stprintf_s(text, sizeof(text), _T("%d"), iDay);
    Correct ?
    ◄◄ hypheni ►►

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: _stprintf_s - Out of bound access

    Quote Originally Posted by hypheni View Post
    Another quick solution would be
    No, that is not a solution. Read up on what a TCHAR is and what sizeof(TCHAR) gives you. That sizeof(text) isn't what you think it is.

    Regards,

    Paul McKenzie

  5. #5
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: _stprintf_s - Out of bound access

    Quote Originally Posted by hypheni
    Correct ?
    Still wrong!

    I wonder why you are searching for "quick" solution instead of a correct and clean one!
    What is wrong with MFC CString?
    Why do you pass in a wrong value of the text buffer size?
    Victor Nijegorodov

  6. #6
    Join Date
    Jul 2009
    Location
    India
    Posts
    835

    Re: _stprintf_s - Out of bound access

    Okay, Correct I missed it.
    ◄◄ hypheni ►►

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured