Thread: Variable shows NAN after return from function call

  1. #1
    Registered User
    Join Date
    Jun 2010
    Posts
    67

    Variable shows NAN after return from function call

    My code has a structure similar to the following simplified pseudocode, with current problematic behavior in CAPS:

    Code:
    main( ) {
        …
        functionA( );
    
    }
    
    
    double functionA( ){
    
         double MyArray[20] = {0.0};
    
         /* code to assign values to MyArray  -- all are valid & verified by print statements */
         … 
         
    
         functionB(…, …, MyArray);
         printf(“Print Statement 1: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
         BEHAVIOR: THE FIRST VALUE OF MyArray (i.e., MyArray[0]) is always NAN here, and the rest of the values look ok. 
    
    
         for(…){
    
                 … /* value of MyArray used but not changed here */ 
                 printf(“Print Statement 2: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
                 BEHAVIOR: ALL VALUES OF MyArray are ok here, including MyArray[0]; however, if I comment out Print Statement 1 above, then the first value of MyArray *here* is NAN, and the rest look ok. So, for some reason, the first value of MyArray[ ] that I print out after the call to functionB( ) returns, is always NAN. 
                 …
        } /* end for( ) loop */ 
    
    } /* end functionA( ) */ 
    
    ________________________
    
    Separate .c code file:
    
    double functionB(…, …, MyArray[]){
    
          printf(“Print Statement 3: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
          BEHAVIOR: SOMETIMES THE FIRST VALUE OF MyArray[ ] (i.e., MyArray[0]) is NAN; during other code runs, this first value is fine. The rest of the MyArray values are ok. 
    
          /* code that assigns new values to the members of MyArray[ ] */
         … 
    
        
         printf(“Print Statement 4: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
         BEHAVIOR: ALL VALUES OF MyArray ARE ALWAYS OK HERE. 
    }

    Does anyone have a suggestion about why the value of MyArray[0] printed at the very end of functionB( ) is always ok, but then the *first* time I print the value of MyArray[0] back in my functionA( ) is always NAN? There is *no* additional code between the return of the functionB( ) call, and when I print out the MyArray values in functionA( )…

    Thanks for any input or debugging suggestions you have.
    Last edited by CodeKate; 11-09-2010 at 04:35 PM.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You are passing myArray as a pointer, but not as a pointer to an array. Add a the squared brackets and size of the array, to the receiving function.

  3. #3
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    Thanks for your response, Adak. Actually, in my original post above, I forgot to add the square brackets after the MyArray[ ] argument to functionB( ) -- these brackets *are* present for all array arguments in my code. I corrected my post above to avoid confusion.

    I tried your suggestion, and added the size of MyArray within the first line of functionB( ) -- unfortunately, I still see the same behavior. (This doesn't surprise me, because I am modifying this code from its previous use, and it had *always* previously worked with just the empty brackets, so I don't believe that this is the problem.)

    The bewildering thing is that I'm modifying my previously-working code, and I don't believe I've changed any of the syntax, which had been working. Any other ideas about what might be wrong? Thanks.
    Last edited by CodeKate; 11-09-2010 at 04:38 PM.

  4. #4
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,059
    Instead of posting the pseudo-code post the actual code, because a lot has to do with what the initialisers are for MyArray[].
    Moreover the NAN output could stem from the fact that you're trying to print a double as a float, tho' to be sure post the code.

  5. #5
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    I'm going to modify my pseudocode from above to provide more of the requested info (because posting the full code would be confusing and too complicated to make sense): (please let me know if any other aspects of the code still need to be added)

    Code:
    main( ) {
        …
        functionA( );
    
    }
    
    
    double functionA( ){
    
         InHouseType *mystructure;
         double MyArray[20] = {0.0};
    
         for(i=0; i < NUM_MEMBERS; i++){
    
         /* code to assign values to MyArray  -- all are valid & verified by print statements */
         /* the following call updates all of the values of MyArray */ 
         mystructure = &InHouse_struct[i];
         printf("Before call to functionB(): MyArray[0]= %f, MyArray[1] = %f, ... .\n", MyArray[0], MyArray[1], ...);
         /* BEHAVIOR: all MyArray[ ] values printed at this point are correct -- no NANs */ 
    
         … 
         
    
         functionB(…, …, MyArray);
         printf(“Print Statement 1: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
         BEHAVIOR: THE FIRST VALUE OF MyArray (i.e., MyArray[0]) is always NAN here, and the rest of the values look ok. 
    
    
         for(j=0; j < NDOF; j++){
    
                 … /* value of MyArray used but not changed here */ 
                 printf(“Print Statement 2: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
                 BEHAVIOR: ALL VALUES OF MyArray are ok here, including MyArray[0]; however, if I comment out Print Statement 1 above, then the first value of MyArray *here* is NAN, and the rest look ok. So, for some reason, the first value of MyArray[ ] that I print out after the call to functionB( ) returns, is always NAN. 
                 …
        } /* end for(j ) loop */ 
    
      } /* end for(i ) loop  */ 
    
    } /* end functionA( ) */ 
    
    ________________________
    
    Separate .c code file:
    
    double functionB(…, …, MyArray[]){
    
          printf(“Print Statement 3: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
          BEHAVIOR: SOMETIMES THE FIRST VALUE OF MyArray[ ] (i.e., MyArray[0]) is NAN; during other code runs, this first value is fine. The rest of the MyArray values are ok. 
    
          /* code that assigns new values to the members of MyArray[ ] */
         … 
    
        
         printf(“Print Statement 4: MyArray[0] = %f, MyArray[1] = %f, …\n”, MyArray[0], MyArray[1], …);
         BEHAVIOR: ALL VALUES OF MyArray ARE ALWAYS OK HERE. 
    }

    >> Moreover the NAN output could stem from the fact that you're trying to print a double as a float, tho' to be sure post the code.
    I've never had a problem using %f to print a double value. Do you see any problems with the way I'm printing out, above?

    Thanks for your help.
    Last edited by CodeKate; 11-14-2010 at 10:20 PM.

  6. #6
    Novice
    Join Date
    Jul 2009
    Posts
    568
    Quote Originally Posted by itCbitC View Post
    Moreover the NAN output could stem from the fact that you're trying to print a double as a float, tho' to be sure post the code.
    In printf() type specifier for both float and double is %f (%Lf is for long double), for scanf() it is %lf, tho.


    @OP
    Could you post the complete function definition for functionB()?

  7. #7
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Confuse us with your code! At least the bare minimum (main, functionA and functionB?) chunk of code that compiles and gives this problematic result. Many of us have been at this for years, and anybody who has worked in industry has likely come across some really horrific, confusing code and had to figure it out. At the very least we could compile it, run it through a debugger (something you should learn about if you haven't yet), and track this thing down. Try us.

    That being said, NaN stands for Not a Number, which usually results from the same mathematical operations that result in invalid numbers in regular (non-computer) math, such as square root of negatives, divide by zero (this one may result in infinity), etc. Here is the Wikipedia article that describes the floating point format and links to info about NaN's: IEEE 754-2008 - Wikipedia, the free encyclopedia. Note that a NaN value is just a particular bit pattern.

    This means that your error could also be a result of some bizarre memory corruption (buffer overflow?) in functionB or something else that functionA or functionB calls, which overwrites the value of myArray[0] in functionA with that magic bit pattern signifying a NaN.

  8. #8
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    You guys are great; thanks for wanting to help.

    >> Could you post the complete function definition for functionB()?
    Pseudocode version of functionB:

    Code:
    double   functionB(InHouseType *v, double Array1[], double MyArray[]){
    
        printf("Start of funcB: MyArray[0] = %f, MyArray[1] = %f, ...\n", MyArray[0],MyArray[1],...);
        /*BEHAVIOR: usually all values of MyArray[ ] are fine; in the past (*possibly* still relevant?), first value of MyArray[ ] (MyArray[0]) is printed as NAN */
        /* So, at least sometimes, it appears that the wrong value of MyArray[0] is being *passed into* functionB( ) -- possibly this value is being changed 
            as it is passed between functionA( ) & functionB( ) ?? */ 
    
        for(i=0; i < VAR; i++) MyArray[i] = 0.0;
    
        /* code to assign value to MyArray[ ] members */
        ... 
    
         printf("End of funcB: MyArray[0] = %f, MyArray[1] = %f, ...\n", MyArray[0],MyArray[1],...);
        /* BEHAVIOR: *All* values of MyArray[], including MyArray[0], *always* have real/correct values here */
    
     } /* end functionB( ) */

    >> This means that your error could also be a result of some bizarre memory corruption (buffer overflow?) in functionB or something else that functionA or functionB calls, which overwrites the value of myArray[0] in functionA with that magic bit pattern signifying a NaN.

    Thanks for suggesting this possibility. I have considered it myself. What puzzles me is that at the very end of functionB( ), MyArray[0] always has a valid value.... and then as soon as I return to functionA( ) and print out the MyArray[0] value immediately after the return from functionB( ), somehow this value is already corrupted/overwritten. I'm just not understanding what might be happening in this short span of code, to cause this behavior...
    Last edited by CodeKate; 11-15-2010 at 12:45 PM.

  9. #9
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Okay...I understand the unlikeliness of the memory corruption, but I'm going to ask again for a complete, no-pseudo-code listing, even if it is confusing. That is, unless you work for some 3 letter agency and posting the code would threaten national security. There is something happening that we can't glean from your pseudo-code and I'd like to run the real program through a debugger and see if I can pinpoint the problem that way.

  10. #10
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    >> Confuse us with your code! At least the bare minimum (main, functionA and functionB?) chunk of code that compiles and gives this problematic result.

    I'm hoping that my psedocode above will do the trick; as it happens, my code is a combination of previous code that I had written that had worked fine, calls to an existing library of working code, and recent changes I've made to my code for a new application, which appear to have caused these new problems.

    I didn't make any changes to how functionB( ) is called from within functionA( ); so I'm not sure why the value of MyArray[0] would be getting corrupted, if this call worked ok in the past. I am suspecting that an array is improperly declared (too-small size, etc.), but so far haven't been able to discern the problem.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,412
    Quote Originally Posted by CodeKate
    I'm hoping that my psedocode above will do the trick; as it happens, my code is a combination of previous code that I had written that had worked fine, calls to an existing library of working code, and recent changes I've made to my code for a new application, which appear to have caused these new problems.
    The problem is that pseudocode may be useful for describing an algorithm, but it is not useful for debugging an implementation of a correct algorithm. Even C code that is not what you are actually compiling and running is not useful for debugging such an implementation. You need to post either the actual code, or a reduced version (the smallest and simplest version, if you can) that also exhibits the same problem in the same way when it is compiled and run.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Quote Originally Posted by CodeKate View Post
    I'm hoping that my psedocode above will do the trick;
    Clearly it hasn't yet. I don't see anything wrong with the pseudocode, and I suspect nobody else did either. Psuedocode hides all sorts of little errors. It's only good for checking overall logic and approaches to a solution. I took a very blind stab at what could cause your problem, and that's about all I can do without a listing.

    Quote Originally Posted by CodeKate View Post
    I didn't make any changes to how functionB( ) is called from within functionA( ); so I'm not sure why the value of MyArray[0] would be getting corrupted, if this call worked ok in the past. I am suspecting that an array is improperly declared (too-small size, etc.), but so far haven't been able to discern the problem.
    Hence you providing us with enough of your code to compile a program and test it ourselves will help us help you track down your problem. Not knowing how these variables are declared, etc makes this impossible to debug. Also, if it's a really large amount of code, please attach the files, or if it's a lot of files, please zip them up before attaching.

  13. #13
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    No, no top-secret government work here... just proprietary code written by other members of my group, which would be frowned upon for me to share (i.e., not my own intellectual property). The big problem is that the whole system of library files is needed to run the code -- separating out individual functions won't compile. I'll think about what my code-sharing options are, and post again soon; thanks again.

  14. #14
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Ahh...you should've just said it was proprietary. Anyhow, I wouldn't go violating any NDAs or copyrights or whatever, unless there's no other choice, or your employer/copyright owner/whoever-has-the-legal-authority says you can. But that really limits our options.

    If you can run this through a debugger, you can put a watch statement on the value at MyArray[0], and just let it run through. Any time that value changes, execution will stop, and you can see what line of code is scrambling your array. I *think* the command in gdb is "watch &(MyArray[0])". The address operator is so that the watch statement continues to work even if you go into a function for which the name MyArray isn't defined.

    One big caveat, this will slow down your program immensely. If you're having a timing-related problem, it might "magically" disappear when using the debugger/watch statement.

  15. #15
    Registered User
    Join Date
    Jun 2010
    Posts
    67
    >> Ahh...you should've just said it was proprietary.

    Thanks for understanding; I should have mentioned this fact sooner.


    >> If you can run this through a debugger, you can put a watch statement on the value at MyArray[0], and just let it run through.

    Good advice. Not to completely change the topic of this thread, but I have a couple of questions about the gdb debugger (sorry to ask here, but gdb doesn't have an online forum, and their email list seems to be directed more toward advanced topics):

    a) I'm compiling and running my code using Cygwin. Is gdb compatible with my current setup?

    b) In the past I downloaded the gdb debugger package, but can't figure out how to actually use the debugger -- there doesn't appear to be an executable to open, and the User Manual focuses on specific functions of the debugger, rather than how to initially get it up and working. With all of the gdb files now sitting in my C:\Program Files\... directory, how can I actually use the gdb debugger? Do I need to copy all of my code into one of these C:\Program Files\gdb\ directories? If anyone is aware of a good link to a gdb *setup* tutorial, I'd appreciate it.

    I agree that a debugger is my best bet to solve my current problems.

    >> One big caveat, this will slow down your program immensely. If you're having a timing-related problem, it might "magically" disappear when using the debugger/watch statement.

    Thanks for the warning; I'll keep it in mind, although I suspect that timing isn't the issue here.
    Last edited by CodeKate; 11-15-2010 at 10:02 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Help calling function is asm
    By brietje698 in forum C++ Programming
    Replies: 24
    Last Post: 12-06-2007, 04:48 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM