Cross-border access issues for new in C + + _c language

Source: Internet
Author: User

Today, when I hit the code, I found a bug to share with you, and I hope everyone will not commit the same mistake as me next time.

If you make the same mistakes as me, you can know where you are wrong! < (^) >

The function is as follows: (Implementation of the Fibonacci sequence)

Long long fibonacciseq (int n)
{
long long *fib=new long long[n+1];
Fib[0] = 0;
FIB[1] = 1;
for (int i = 2;i <=n; i++)
{
Fib[i] = fib[i-1] + fib[i-2];
Long LONG ret = fib[n];
Delete[] FIB;
return ret;
}

The above program has bugs, and if the argument to the function is 0, the program crashes because it triggers a breakpoint.

Single-step debugging, depending on the memory window will find the problem!

After the fib point to memory initialization is complete, its memory as shown above, we can observe this block of memory before and after FD FD FD, 0xFD for the initialization of protected memory (debug version in the dynamic allocation of memory before and after the memory to protect against cross-border access), while fib[1] = 1; The FD FD fd and the four bytes after it have been changed to 01 00 00 00 00 000000, as shown below:

The program ran to delete[] fib, only to find the "protected memory Flag" start location, another "protected memory flag" can not be found, so the program run will fail!

In fact, it is very simple, that is, cross-border access! I only new a piece of space, but saved two variables, of course not!

Related Article

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.