I was practicing about structs in C, so I've tried to execute 2 times this code and twice the computer crashes. I've had turn off the computer twice since my computer crashes.
Compiler is GCC (About MinGW on windows platform). The code is following :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct person {
char name[50];
int age;
int document;
};
int main(void){
struct person p1;
printf("Data of the first person\n\n");
printf("age: ");
fflush (stdin);
scanf("%i",p1.age );
printf("Document: ");
fflush(stdin);
scanf("%i",p1.document);
printf("Age is: %i and document is: %i ",p1.age,p1.document);
return 0;
}
Sincerely,
NIN.
UPDATE....
Bad news. Now Avast says I`ve created a virus. Therefore Avast delete my exe:
Should I report as false positive or not ?
scanf("%i",p1.age );
When you call scanf, p1.age is an integer with no particular value. So you are asking scanf to store the value you input in no particular place. It's not surprising this causes a crash. You want:
scanf("%i", &p1.age );
This tells scanf to read in an integer and store it at the address of p1.age.
It's surprising your compiler didn't give you a warning. Are you sure you have all of its warnings enabled?
When I try to compile this, I get appropriate warnings:
warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
Update: Your anti-virus has heuristics that block software that has suspicious behavior. Your code has bugs, and your anti-virus doesn't know that they're just mistakes and not attempts to do something nefarious. It sounds like you don't have a very good environment set up for experimentation. Let me guess -- you're doing all this from a Windows administrator account.
Related
This question already has answers here:
Visual Studio Code: Take Input From User
(6 answers)
Closed 5 months ago.
I got used to printf and variables in C, then I started to use the scanf function, here's the code (shamelessly stolen from fresh2refresh.com)
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
Except that it doesn't run, neither on the vscode output or cmd. it doesn't even print the "Enter any character" from line 5, it show that the code is running, but doesn't even accept inputs (and will only halt once I click the Stop Code Run button)
any tips?
The line
scanf("%s", &str);
Is incorrect - it should be
scanf("%99s", str);
So
It has bounds - i.e. not array over bounds
It is passing a char *
BTW - Might be a good idea to check the return value from scanf
You can choose: Run->Add Configuration... -> launch.json
change this: "externalConsole": true,
Recently I encountered the same problem.
So here's the fix :
In visual studio code, go to extensions and download "Code Run by Jun han"
Then go to the extension setting >> scroll down >> and click on Run in Terminal
You may reopen your vs code or else skip this step.
Now, try running the code again.
Hope it helps!!
I had the exact same problem and what worked for me was installing Code Runner and then go to the setting of your visual studio code. Search "Run In Terminal" and then make sure the Code Runner: Run in Terminal box is checked.
That fixed my issue.
format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[100]’ [-Wformat=] scanf("%s", &str);
Strings are represented as Array of characters thus array name is an identifier(implicit conversion to pointer) is the address of first element thus no need to specified '&' in case of reading strings.
Its clear from warning that it can't convert from char (*)[100] to char *
In C, a string is the address of the character buffer which is why we do not need "&" with the variable.
Code with solution
My English is poor. I wish I can help you!!
scanf("%s", &str);
this sentence is false.
Do you know pointers, or Memory address?
If you know, suppose you are the creator of scanf. What you need to do is read what the user write in the screen and copy them to the space of the second argument.
So, you don't care about the value of the second argument. What you care about is the address of the second argument. Then you can access this memory space.
So, when the second argument is a variable, such as int a, you need to "&a".
But str itself can be a address. So it do not need "&"
Here in this code, when I execute it, it sometimes display correct value of nT and nF, sometimes it display correct nF but incorrect nT(i.e 0).
Why is it so??
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
unsigned char nT,nF;
puts("Enter No. of Testcases & Faults");
scanf(" %hhu %hhu",&nT,&nF);
printf("\n %hhu %hhu",nT,nF);
}
You need to use %hhu as the format specifier for an unsigned char. (Obscure I know: one for the pub quiz.) Also, you might want to introduce some spaces between your formatters:
int read = scanf("%hhu %hhu %s", &nT, &nF, extension);
Currently the behaviour of your program is undefined.
Prior to C99 you're pretty much at the mercy of your compiler.
Further notes:
Always check the return value of scanf which gives you useful information about the number of inputs that are read successfully.
extension is only good for 4 characters plus the nul-terminator.
I am writing a simple C program to accept an input number from user and display it just because earlier i was writing some C program and this stupid error is bugging me it wasn't there before until yesterday
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a;
printf("Enter a number");
scanf("%d",&a);
printf("Display number%d",&a);
}
Every time i run a program that accept an input it displays a seemingly random value and not the one I entered not just in this program in any other too, here
is the O/p:
Enter a number: 12
Display number : 2752300
Process returned 7(0X7) execution time : 1.880s
Press any key to continue
I don't know whether is the Compiler error or some memory error that is causing this problem but for the record i have tried using different IDE like DEV C/C++, Turbo C/C++ and Code Blocks but the error remains to be same in all of it except in Turbo C/C++ it display a signed number of i enter for eg : if input is 12 it displays: -12.
The problem is in your print statement. You are printing the address of a, not the value. Use print("%d",a);
The %d format specifier for printf expects an int, not an int *:
printf("%d",a);
It's not attempting to write to a, so it doesn't need its address.
If you compile with the warning level turned up (-Wall -Wextra for gcc), it will tell you this:
format ‘%d’ expects type ‘int’, but argument 2 has type ‘int *’
scanf needs a pointer to the variable if it is going to change the variable itself, so we use the address-of operator to get the pointer.
scanf() received "%d", as a parameter and then knows it needs to read an integer and store it in the next variable in the argument list.
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a = 0;
printf("Enter a number: ");
scanf ("%d" ,&a);
printf ("%d \n ",a);
return 0;
}
I am attempting to read in a sentence from the user and make it into an array, where each letter holds a character value. Each time I run the program, I am able to type in the sentence, but after that "Segmentation Fault (core dumped)" appears. All of this is happening within a function that is called from the main.
int words(char sentence[]){
int i=0;
printf("Please enter your favorite sentence(max 100 characters).\n");
scanf("%c", &sentence);
while(sentence != "." && sentence != "!"){
i++;
scanf("%c", &sentence[i]);
}
printf("%d", i);
return i;
}
What does your compiler say when you compile with -Wall -Wextra. You can't expect to write C code correctly without compiling with warnings on. Everyone says how badly you can mess up with C code, it lets you do anything. That's true but the warnings are there to help you.
I'm not sure why people are asking you to go to gdb or valgrind. For me, this code should never be executed and expect to be right. My compiler spits out these warnings:
words.c: In function ‘words’:
words.c:6: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char **’
words.c:7: warning: comparison with string literal results in unspecified behavior
words.c:7: warning: comparison with string literal results in unspecified behavior
Fix those warnings and then come back if you are still having problems. Or if you don't understand what those warnings mean then ask a specific question about it.
Change your code to this and it will work:
char sentence[30];
int i=0;
printf("Enter phrase: \n");
scanf("%c", sentence);
while(sentence[i]!='.' && sentence[i]!='!')
{
i++;
scanf("%c",&sentence[i]);
}
printf("%d\n", i);
return i;
You just had to remove the '&' from the scanf in the fourth line since sentence alone without the array index indication is a memory adress itself. Note that this works if the sentences always end with a '.' or a '!'. Although i believe there is a better way to do this than reading the sentence one char at a time.
I am writing following c code and getting an error :
#include<stdio.h>
#include<stdlib.h>
int main()
{
char *prot;
char addr[20];
FILE *fp;
int i = 0;
int tos,pld;
prot = (char *)malloc(sizeof(char *));
//addr = (char *)malloc(sizeof(char *));
printf("\n enter the protocol for test::");
scanf(" %s",prot);
printf("\n enter the addr::");
scanf(" %s",addr);
printf("\n enter the length of the payload::");
scanf(" %d",pld);
printf("\n enter the tos :: ");
scanf(" %d",tos);
I am getting the following error while entering the value.There is a segmentation fault coming could anyone tell me why this segment fault is coming:
enter the protocol for test::we
enter the addr::qw
enter the length of the payload::12
Segmentation fault
prot = (char *)malloc(sizeof(char *));
Should be:
prot = malloc(sizeof(char) * SIZE); // SIZE is the no. of chars you want
Another problem is: You should use & for integers in scanf()!
With changes:
printf("\n enter the length of the payload::");
scanf(" %d",&pld);
printf("\n enter the tos :: ");
scanf(" %d",&tos);
The segmentation fault is because scanf expects a pointer to the variable the scanned value shall be stored in, but you pass the variable pld itself. That is uninitialised and hence when interpreted as a pointer points into the wild. The same happens with the tos. And of course, you should allocate the proper amount of space for prot as has otherwise been pointed out.
Your memory allocation for prot has allocated 4 bytes (on a 32-bit system) or 8 bytes (on a 64-bit system) for the string. If you read more than that into it, you are overflowing your buffer.
Unless there was a good reason to do otherwise, I'd simply use:
char prot[128];
for any suitable size for the string.
You should also check all your scanf() calls to ensure they succeed; you should probably apply a limit to the size of the strings. For a char prot[128];, the safe conversion is %127s; the null is not counted in the conversion specification.
If your compiler was not warning you about these lines:
scanf(" %d",pld);
scanf(" %d",tos);
you either need to turn on more warnings or get a better compiler. If it was warning you, pay heed to your compiler; it knows more about C than you do (and probably more about it than I do, too).
scanf(" %d", &pld);
scanf(" %d", &tos);
This is probably not the source of your current problem, but it is a bug:
prot = (char *)malloc(sizeof(char *));
I doubt you meant to make a buffer the size of one character pointer.
Anyway, to pinpoint your immediate issue, please run your program under valgrind and/or a debugger. In this particular case just enabling compiler warnings would have caught your problem, which is that you're passing integers by value where you should be passing by pointer to scanf. This could have been solved by the compiler, instead of coming to us, if only you enable the relevant options.
scanf expects pointers to the variables you're filling (except in the case of strings, which are already pointers to char).
Try
scanf(" %d", &pld);
and the same with tos.
scanf family of functions are main source of problems in homework.
They always expect addresses, so they can be used as OUTPUT.
They cannot be type-checked because the prototype of that part is ..., so you can put anything there. compiler does not complain.
When things don't work, check the receiver arguments, they need to be address of items to be written into, and the type has to match what your specify in the format string.