简体   繁体   中英

Function abruptly returns when it shouldn't

I am working on an Operating Systems assignment for one of my summer classes. The teacher has provided an object file that provides functions that mimic the behaviour of a disk device driver. We are then to write a file system API that uses the disk device driver in C.

I am working on my file system format function named Format() which calls a function named DevFormat() from the teachers object file. My function is supposed to return 1 if it was able to successfully format the file system and 0 otherwise. DevFormat() returns 1 if it was able to successfully format the disk drive and 0 otherwise. Here is come code:

int Format()
{
    if (!DevFormat())
    {
        printf("Disk drive wasn't formatted successfully\n");
        return 0;
    }

    <Do some stuff to the file system here>

    printf("File system successfully formatted\n");
    return 1;
}

My problem is that Format() just abruptly ends without returning a value. I have found that the offending piece of code is the line: if (!DevFormat()) . Now I am writing the assignment in C but am using the GNU C++ (g++) compiler to compile and link my project as the teacher said we could. I want to say that the reason Format() abruptly ends when the line if (!DevFormat()) is executed has to do something with the compilers interpretation of my code (I could be way way off. Its just a guess.). I found that my function abruptly ends as well if I change the code to if (0 == DevFormat()) . The only way I can test for failure is by assigning the return value of DevFormat() to an int variable and then checking that.

Any help would be much appreciated. Is it something to do with the way the C++ compiler interprets my code? Is it I missed something so mundane that I should be ashamed of myself?

Thanks again for the help.

I think maybe you have forgotten the braces around your if statement - I imagine you meant to write this:

if (!DevFormat()) {
    printf("Disk drive wasn't formatted successfully\n");
    return 0;
}

Only the printf statement was inside the if block, so the return statement was executed every time regardless of the return value of DevFormat(). That's a common gotcha in C :)

这肯定是一个错误,但我没有在上面的代码中看到任何缺少的大括号 - 是否已被编辑?

Try compiling with gcc -fno-exceptions and see if that changes anything. (Recomile the library too, just to be sure.) Also, I second @tholomew's request for elaboration on "Format() just abruptly ends without returning a value.".

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