Search code examples
c++fopenassertionsprintf

fprintf debug assertion fail


I have a program that runs correctly if I start it manually. However, if I try to add a registry key to start it automatically during startup, I get this error:

Debug assertion failed (str!=null) fprintf.c line:55

I tried to add Sleep(20000) before anything happens, but I get the same error.

Here's the code:

main()
{
    FILE* filetowrite;
    filetowrite = fopen("textfile.txt", "a+");

    writefunction(filetowrite);
}

int writefunction(FILE* filetowrite) {

    fprintf(filetowrite, "%s", "\n\n");
    ...
}

I also tried passing the filename as char* and opening it in writefunction(), but I get the same error.


Solution

  • The fopen is failing. You should always check the return value to see if it works:

    filetowrite = fopen("textfile.txt", "a+");
    if (filetowrite == NULL) {
        // log something, including errno
        exit (1);
    }
    

    Line 55 of fprintf.c in VC++ is:

    _VALIDATE_RETURN( (str != NULL), EINVAL, -1);
    

    where str is the FILE * argument (nice variable name, Microsoft, what on Earth were you thinking?).

    I suspect there may be permissions problems or something similar with trying to run it via the registry (presumably under Run or RunOnce or as a service).

    Once you've figured out what the actual error is, the solution should be easier to produce.

    If it's a matter of permissions, you should be able to find that out by using something like c:\\a\\directory\\i\\KNOW\\i\\can\\write\\to\\textfile.txt and seeing if it works. Then you can also use that file for logging things like the current directory.

    If it simply turns out the "background" starting method is in the wrong directory, change directories as one of your program's first actions.