Please tell me where I've gone wrong - c

#include <stdio.h>
main()
{
char name1[15],name2[15],name3[15];
int no;
printf("Enter the serial number and name one\n");
scanf("%d %15c',&no, name1");
printf("%d %15s\n\n",no,name1);
printf("Enter serial number and name two\n");
scanf("%d %s",&no,name2);
printf("%d %15s\n\n",no, name2);
printf("Enter serial number and name three");
scanf("%d %15s",&no,name3);
printf("%d %15s\n\n",no,name3);
}
Hi, I'm new to programming, I've started with C for some reasons. The code I've typed above is my program that I want to execute. When I execute it with Code::Blocks it runs till Enter the serial number and name one and then if I enter a number it become not responding. Then I tried compiling using Visual Studio 2013 it again stops responding.
After that I tried debugging using Visual Studio 2013 debugger it said this First-chance exception at 0x7575B790 (msvcrt.dll) in temp.exe: 0xC0000005: Access violation writing location 0x00000000. after pressing continue it said this Unhandled exception at 0x7575B790 (msvcrt.dll) in temp.exe: 0xC0000005: Access violation writing location 0x00000000.
I have programmed before this one in Code::Blocks they all worked well. Please tell me where I've gone wrong. Also please explain the use of %s.
Thanks

scanf("%d %15c',&no, name1");
Should be replaced with:
scanf("%d %14s",&no, name1);
Use double quotes since the single quote doesn't terminate a String in C.
Use %14s (as suggested by chux) so that you do not overflow the buffer for the string and cause a seg fault
%s is used to read in a space delimited string. If you want to read an entire line, you must make use of fgets function

Related

Exception thrown in strings input output

I had been having an issue with string in school project and couldn't manage to fix it, made a test program to troubleshoot but haven't had any luck. I'm trying to just make a simple program to take a string value and then print it to the console. When it tries to print the string the program crashes with an exception being thrown I don't understand I think it is trying to save the string data to a memory address it doesn't have access to but im not sure cuz I tried it on both my laptop and pc with the same issue.
"Exception thrown at 0x00007FFAACA60369 (ucrtbased.dll) in tokenizing.c.exe: 0xC0000005: Access violation writing location 0x0000001F1F100000."
#include <stdio.h>
int main() {
char string[100];
printf("Enter a string: ");
scanf_s(" %s ", &string);
printf(" %s ", string);
return 0;
}
scanf_s(" %s ", &string); fails as it is missing a parameter. %s obliges a pointer and size.
scanf_s(" %s ", string, (rsize_t) 100);
Review your compiler details on scanf_s() as the C standard is not followed in details by some compilers.
Alternative: Review fgets() to read a line into a string.
A space before "%s" serves no purpose. Best to drop it.
A space after "%s" blocks until following non-white-space detected. Best to drop this space too.

why strcmp function is not giving correct comparison result in c program

So below is my source code in c in which i have used strcmp function to compare two strings
#include<stdio.h>
#include<string.h>
int main() {
unsigned char pass[100]="Try to hack me";
unsigned char input[100];
printf("Enter the secret string: ");
scanf("%s",input);
if(strcmp(pass,input))
printf("Wrong Password\nAccess Denied\n");
else
printf("Right password\nAccess Granted!!\n");
return 0;
}
when i run the compiled program it is giving wrong output, it suppose to give the right messasge but its giving wrong message. what is the problem here?
below is the output response of the program
professor#CTOS:~/Documents/Bnry/elf32bit/Module3/ch6$ ./crackme
Enter the secret string: Try to hack me
Wrong Password
Access Denied
professor#CTOS:~/Documents/Bnry/elf32bit/Module3/ch6$ ./crackme
Enter the secret string: Try to hack me
Wrong Password
Access Denied
%s in scanf only reads until a white space character. From “Try to hack me”, it only reads “Try”. Use a different method to read the input line, possibly fgets, but be aware that fgets includes the new-line character that terminates the line.
When your program does not work, debug it. Either trace execution with a debugger or insert printf statements to show what it is doing. Inserting printf("The input is %s.\n", input); after the scanf would have revealed the problem.

Performance - C program takes way longer to run on VS code (windows 10)

I have just installed visual studio code & after watching some basics, I have written a simple C code to calculate area of rectangle. But, when I run the code its taking too long to execute.
My system configuration are 4gb RAM, i3 - 5th gen (poor boi) Here is the code:
#include <stdio.h>
int main()
{
int l;
int b;
printf("enter the length of rectangle in an integer value");
scanf("%d ", &l);
printf("enter the breadth of rectangle in an integer value");
scanf("%d ", &b);
printf("the area of rectangle is %d", l * b);
return 0;
}
Change scanf("%d ", &l); to scanf("%d", &l); and scanf("%d ", &b); to scanf("%d", &b);.
A space in a format string tells scanf to read from input until a non-white-space character is read. So, after scanf("%d ", &l);, the program continues reading input until you type something such as the next number. If you do type that next number, then scanf("%d ", &b); reads it and then continues reading until it sees another character that is not a space. As long as you do not type anything, or type only spaces and returns/enters and other keys that generate white space characters, the program continues waiting.
Removing the spaces eliminates this.
The program is not “taking too long to execute.” In fact, the program is waiting for user input, so it is just waiting, not executing. Because it did not complete, you concluded it was taking too long to execute. Instead of reporting a conclusion, you should have reported the observed behavior: After typing input, there was no visible activity by the program.
Skipping spaces before performing a conversion is built into most scanf conversions, such as %d. Only include a space character in a format string where you want to skip spaces that would not be skipped normally, such as before a %c conversion, which does not have the automatic skipping built in.
Also, in printf("the area of rectangle is %d", l * b);, add a new-line character at the end, printf("the area of rectangle is %d\n", l * b);. (This ensures the prompt printed by a command-line shell after the program finishes executing is on a new-line, so it will not be confused with the program output. C is designed to end lines of output with new-line characters, so you should make it a regular practice.)
Alright guys, I found the solution. The first thing I want to apologize is that the code is not taking too long to execute. The code is actually executing but there was no visible activity. Everything in the code is just perfect. The mistake I made is I didn't change one setting in VS Code. I use code runner extension to run my codes [that's the most popular]. I have to go in File --> Preferences --> Settings --> Type 'code runner' in the search bar --> check the setting given in this image - https://drive.google.com/file/d/1QwB2NjKpYX7M0b5w55sqy4oMVAOk_IK2/view?usp=sharing
Lot of people were trying to figure out a mistake in the code, but there is nothing wrong with it. Code runner was not able to run in the terminal, so there was no activity to take any user input - due to read only text editor. After changing that setting I was able to give user input directly in the terminal.
Credit for the solution - https://www.youtube.com/watch?v=Si8rN5J249M
EDIT: There is a mistake in my code also lol, which is mentioned in another answer - Really appreciate it Eric Postpischil

In Visual Studio 2013, "Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted."

I would first like to thank you for looking into my question.
I have been coding using Code Blocks ever since I started coding with C, and recently I had to switch to using Visual Studio for my college lab assignments. We had a pretty easy assignment this week, but I seem to keep running into this error that ONLY pops up when using Visual Studio, and not in any other IDEs. I was wondering if someone could help me resolve this issue, and tell me what I am doing wrong? I will attach my code below.
Thank you so much!
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
void main()
{
srand(time(NULL));
int a, n;
char b ='y';
while (b == 'y')
{
n = rand() % 3000 + 1; // 1-3000
puts("I have generated a number between 1 and 3000. Can you guess mynumber?\nPlease type your first guess (0-3000):");
scanf("%d", &a);
while (a != n)
{
if (a > n)
printf("Too high. Please try again.\n");
if (a < n)
printf("Too low. Please try again.\n");
scanf("%d", &a);
}
printf("Excellent! You guessed the number!\n");
printf("Would you like to play again? (y or n)\n");
scanf("%s", &b);
}
printf("Have a nice day.\n");
system("PAUSE");
}
This code is designed to generate a random(ish) number from 1-3000, and have the user guess it. The user then has the option to choose to play again or not. The error occurs when the user types 'n' to end the outer while loop.
Thanks again!
Heed the dangers of scanf:
scanf("%s", &b);
b is a char, yet you gave scanf the specifier of %s. The %s specifier is for character buffers, not single chars. What is happening is that scanf assumes that b is a pointer to a buffer, and thus you get a memory overwrite.
You should specify %c as this is the specifier for a single char.
Also, just because you didn't see this in Codeblocks (probably using gcc) doesn't mean the program was ok, and it is only Visual Studio has a problem. The program was wrong, and what you observed is undefined behavior. When you overwrite memory, anything can happen, including "working ok".

scanf("%d") works correctly with character

The code is:
int main() {
scanf("%d");
puts("hello!");
getch();
return 0;
}
If I input a number like 7, the program crashes but if I input a character like h, the program executes successfully.
Could you please explain me the reason behind it?
I am using MinGW on Windows XP.
Access specified %d won't get other character except number.
If you give other character the scanf get executed and nothing will store.
When you give numeric character the scanf get executed and try to store the value.
Due to storage location is unavailable the program get crashed.
Try to use the storage location in the scanf like
scanf("%d",&a);
The every version say warning to storage location.
So try to check warnings.
Compile with the warnings.
Read the manual page you will not that scanf("%d"); will require an address to put the number into if there is one
Try
int x;
scanf("%d", &x);
You should also check the return value from scanf as per the manual page. I leave that as an exercise to the reader to do with as he will.
Try
check = scanf("%c %d",&a, &b);
printf("check = %d \n",check);

Resources