Sprintf () may cause cross-border errors

Source: Internet
Author: User

Sprintf () may cause an out-of-bounds problem. When releasing the memory, an error will be reported during the delete operation. Pay attention to this when using it.

 

For example:

First, create a character array and allocate memory to it.

Char * TMP = new char [255];

Memset (TMP, '/0', 255 );

 

Use sprintf () to copy char * Data to TMP. The data length exceeds 255:

Sprintf (TMP, "Data = % s", data );

 

The following error is generated during Delete [] TMP:

 

Char * TMP = new char [255]; <br/> file * fp = fopen (tmpfile, "R"); <br/> If (FP = NULL) {<br/> afxmessagebox ("Open File error"); <br/> return 0; <br/>}< br/> // 1. read the file content <br/> char * Data = new char [1024*10]; <br/> memset (data, '/0', 1024*10 ); <br/> int K = 0; <br/> int Total = 0; <br/> while (! Feof (FP) {<br/> K = fread (Data + total, FP); <br/> total + = K; <br/>}< br/> fclose (FP); <br/> sprintf (TMP, "Data = % s", data ); <br/> afxmessagebox (TMP); <br/> Delete [] TMP; <br/>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.