• 0

what is the difference between these two programs?


Question

What is the difference between these two programs. I read in a book that the first method is better but isn't there larger use of memory?

First

#include<stdio.h>
#include<string.h>
int main()
{
	char line[100];
	int value;
	printf("Enter the Number to be doubled : ");

	fgets(line,sizeof(line),stdin);
	sscanf(line, "%d", &value);

	printf("The double of the number is %d \n",2*value);
	return(0);
}

Second

#include<stdio.h>
#include<string.h>
int main()
{
int value;
printf("Enter the value\n");
scanf("%d",&value);
printf("The double of the number is %d",2*value);
}

8 answers to this question

Recommended Posts

  • 0

Some people seem to think that fgets is inherently safer, personally I have strong doubts about it. In any case the first program also uses scanf and does no validation on the input before calling scanf; it doesn't validate that fgets nor scanf succeeded, so it's just as terribly error-prone as the second one. And, as you mention, the first one also uses 100 extra bytes on the stack for nothing.

I suppose the point of using fgets before scanf is to do some kind of validation... which doesn't happen here.

Edited by Dr_Asik
  • 0

Neither is a good example. In the first you're allocating 100 bytes on the stack for a integer value which is probably a maximum of 4 bytes. And the second example you're at the mercy of the user as you're hoping they enter a valid integer.

As far as I'm aware fgets() is used to ensure you don't retrieve more bytes than you can store in a buffer. This provides some validation but in no way shape or form ensures the user has entered a valid value.

  • 0

ok.. let's assume that we used 4 bytes in line char..

so now is it better than the second one..?

in the first program we two functions to get the input whereas in the second one we only use one function for storing the input.. isnt it better now?

plus what is the difference between scanf and sscanf??

  • 0

As I said, both programs are very error-prone because both scanf and fgets can fail and neither checks for that. If you need safe input, it's pretty complicated in C... IMO any input in a C program should be debugging purposes, if you need reliable, end-user input, use a better programming language like Java, Python, C# or whatever. (or take the time to learn it properly in C : http://www.friedspace.com/cprogramming/safeinput.php more nice advice at http://www.daniweb.com/tutorials/tutorial45806.html#)

I suggest you read the description of these functions here:

fgets

scanf

sscanf

It's when you have to deal with this stuff that you realize how pathetic C is for general application programming; it's a thin, thin layer over assembly, nothing else, you're still coding tons of error-prone, complicated logic for the most basic tasks. Anyway I disgress.

Edited by Dr_Asik
  • 0
I read in a book that the first method is better

Well, what reason does the book give?

Neither is a good example. In the first you're allocating 100 bytes on the stack for a integer value which is probably a maximum of 4 bytes.

He's allocating 100 bytes for a string representation of a character, which could easily exceed 4 bytes. 4 bytes is if the integer is stored as an integer, and for that, he is already allocating exactly 4 bytes on the stack.

Not that 100 bytes on the stack means that much. Yes, it's a bit more memory, but this is the stack, not the heap, and the stack is pre-reserved and often pre-committed at the start of your thread (this could vary by OS, of course), so unless this pushes you past the range of committed pages on the stack, it doesn't matter one bit if you allocate 1 byte or 1000 bytes.

plus what is the difference between scanf and sscanf??

Read the documentation.

Although the specifics vary from implementation to implementation, generally speaking, sscanf is implemented using scanf or vice-versa. In the Windows CRT, for example, sscanf just creates a dummy stream from the string and passes all that along to scanf. For the book to say that fgets+sscanf is somehow inherently better than scanf suggests ignorance on the part of the book's author. Unless you have a specific need to work with the string--perhaps to do additional custom processing or checking before running the scanf--there is no point in doing what the author is suggesting. In either case, you'll need to do input checking--you can't escape that.

  • 0
It's when you have to deal with this stuff that you realize how pathetic C is for general application programming

:p Not that a lot of general application programming these days operate on console input...

Edit: Okay, I see his thread about doing network in C. Oh, that oughta be fun...

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft finally admits its default Windows 11 25H2, 24H2 action broke key legacy component by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. So far the company has acknowledged two known issues that have popped up after the release which include bugged-out Office apps as well as the Recycle Bin; though there could be more at play too. Speaking of bugs and issues, Microsoft seems to have finally acknowledged a problem that probably has been around for close to a year. That's because back in July of 2025 the company made a default change to the latest Windows 11 versions, wherein it switched to JScript9Legacy on Windows 11 24H2 and later releases. Hence following the release of version 25H2 in October 2025, JScript9Legacy also remained default-enabled. As a result there has been a compatibility issue ever since then. For those wondering, by switching to JScript9Legacy Microsoft intended to improve the security of modern Windows PCs by reducing vulnerabilities tied to legacy scripting like cross-site scripting (XSS), among others. XSS exploits can allow cyber-attackers to attach malicious code onto legitimate websites and use them to execute the code when a potential victim loads such a website. Hence the new JScript9Legacy engine enforced stricter execution policies and improved object handling, which should help mitigate such attacks. Microsoft today has published a new support article detailing the problem. Neowin spotted it while browsing. The company says that JScript global definitions and execution context may fail to persist across scripts, potentially breaking older dependent apps and web-based components that relied on this legacy behavior. In the article Microsoft has confirmed that the issue stems from its move away from the older jscript9.dll engine in favor of jscript9legacy.dll. As mentioned above, while the newer engine was designed to address vulnerabilities and strengthen security it also changes how JScript handles execution context. As a result functions and definitions loaded by one script could no longer remain available to subsequent scripts once execution ended. The company notes that some applications worked correctly on earlier Windows versions because the older JScript engine automatically retained global definitions and execution state between scripts. Under the newer model though that behavior is disabled by default causing certain legacy workloads and polyfill-dependent scripts to fail. Microsoft says it addressed the problem via the KB5077241 update though the fix had not been enabled automatically in the following updates. As such admins must explicitly turn on persistent JScript execution context using a Registry setting that the tech giant shared today. The configuration can be applied to individual processes or system-wide through the FEATURE_ENABLE_PERSISTENCE registry key. The steps have been outlined below: Run the following command to create the feature control registry key: reg add "HKLM\Software\Policies\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PERSISTENCE" Under this key, create a new DWORD (32-bit) value. Configure the value as follows: To enable persistence for specific processes only: Set the value to 1 for each target process name. To enable persistence for all processes: Add * as the key name and set its value to 1. You can find the official support article here on Microsoft's website.
    • The possibility that milk gathers back into a glass implies that gravity can be 'reversed'.
    • VidCoder 12.20 by Razvan Serea  VidCoder is a DVD/Blu-ray ripping and video transcoding application for Windows. It uses HandBrake as its encoding engine. Calling directly into the HandBrake library gives it a more rich UI than the official HandBrake Windows GUI. VidCoder can rip DVDs but does not defeat the CSS encryption found in most commercial DVDs. You’ll need the NET 8 Desktop Runtime. If you don’t have it, VidCoder will prompt you to download and install it. The Portable version is self-contained and does not require any .NET Runtime to be installed. You do not need to install HandBrake for VidCoder to work. Feature list: Multi-threaded MP4, MKV containers Completely integrated encoding pipeline: everything is in one process and no huge intermediate temporary files H.264, H.265, MPEG-4, MPEG-2, VP8, Theora video Hardware-accelerated encoding with AMD VCE, Nvidia NVENC and Intel QuickSync AAC, MP3, Vorbis, AC3, FLAC audio encoding and AAC/AC3/MP3/DTS/DTS-HD passthrough Target bitrate, size or quality for video 2-pass encoding Decomb, detelecine, deinterlace, rotate, reflect, chroma smooth, colorspace filters Powerful batch encoding with simultaneous encodes Customizable Pickers to automatically pick audio and subtitle tracks, destination, titles and more Instant source previews Creates small encoded preview clips Pause, resume encoding VidCoder 12.20 changes: Updated HandBrake core to 1.11.2. Download: VidCoder 12.20 | 47.0 MB (Open Source) Download: Portable VidCoder 12.19 | 89.3 MB Link: VidCoder Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Jordan Smith earned a badge
      Week One Done
    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      590
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      76
    4. 4
      Michael Scrip
      73
    5. 5
      Steven P.
      66
  • Tell a friend

    Love Neowin? Tell a friend!