简体   繁体   中英

How to avoid buffer overflow in c

I tried to setup this code to avoid buffer overflow and I'm not sure why it doesn't work. I'm fairly new to this and help would be appreciated.

I've tried using assert to make sure it ends but i want the assert to succeed

void authenticate (void) 
{
    char buffer1[8];
    int i;
    for (i = 0; i < 16; i++)
    {
        assert (i < sizeof(buffer1));
        buffer1[i] = ‘x’;
    }
}

expect assert to pass but it fails. Want to fix it without completely rewriting the loop. Thanks!

There seems to be some misunderstanding here on exactly how assert functions. The assert macro performs a runtime check of the given condition. If that condition is false it causes the program to abort.

In this case, the value of i ranges from 0 to 15 inside of the loop. On the iterations where the value of i is less that 8 the assert passes. But once i becomes 8 the assert fails causing the program to abort. The failed assert will not cause the program to for example skip the next loop iteration.

The proper way to handle this is to limit the loop counter to not go out of bounds:

for (i=0; i<sizeof(buf); i++)

The C language by itself doesn't perform bounds checking like some other languages. That's part of what makes it fast. That also means that the language trusts the developer to not do things like read / write out of bounds of an array. Breaking that trust results in undefined behavior . So it's up to you to make sure that doesn't happen.

There are also tools such an valgrind which will help identify mismanagement of memory.

Assert fails as expected. Change counter limit to 8 to pass.

    for (i = 0; i < 8; i++)

But perhaps you really want

    buf[7]=0;
    for (i = 0; i < 8; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM