Menu

Memory Leaks in scanf (Urgent)

2009-02-26
2012-09-26
  • Inês Oliveira

    Inês Oliveira - 2009-02-26

    The following code is corrupting "month" variable. If you try 2-2009 it prints 0-2009.
    It happens even when I use diferent scanf instructions to read both variables separately.
    I just downloaded Dev-Cpp,so I think it is the latest release.

    Regards,
    Inês

    include <stdio.h>

    int main() {

    unsigned short month, year;
    
    printf(&quot;Insert month and year (mm-yyyy):&quot;);
    scanf(&quot;%d-%d&quot;, &amp;month, &amp;year);
    printf(&quot;%d-%d&quot;, month, year);
    
    system(&quot;pause&quot;);
    return 1;
    

    }

     
    • Inês Oliveira

      Inês Oliveira - 2009-02-26

      Yes it is actually due to the %d (I should have been more precise and use %hu).
      I didn´t think in that because the sample in question worked fine in a previous version.

      Thank you!

       
      • Wayne Keen

        Wayne Keen - 2009-02-26

        Note also that the exact version number for Dev is right on the window frame...

        Wayne

         
        • Wayne Keen

          Wayne Keen - 2009-02-26

          By the way, I tend to give answers that are "hints", where you figure out what is going on. This is not some sadistic game on my part, though it might seem that way to some. Congrats on using the hint to REALLY see what the problem was.

          Wayne

           
    • cpns

      cpns - 2009-02-26

      Add the following compiler options:

      -Wformat -Werror

      and the GCC compiler will be able to trap format specifier mismatches.

      Better yet use C++ iostream instead of stdio, it determines the format directly from the type through overloading. Note that there is no real benefit in using a short unless you need to match some specific file format, communication protocol or hardware register size. In general use plain int anywhere you can, you code will probably end up more robust for that.

      Clifford

       
    • Wayne Keen

      Wayne Keen - 2009-02-26

      Memory leak?

      Try the following code, see if it works. (It does for me) The fflushes are there for me for the environment (Pure MinGW/MSYS) that I am running...

      include <stdio.h>

      int main() {

      int month, year;

      printf("Insert month and year (mm-yyyy):");
      fflush(stdout);
      scanf("%d-%d", &month, &year);
      printf("%d %d\n", month, year);
      fflush(stdout);

      system("pause");
      return 1;
      }

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.