I am learning C, it's my first programming language. I don't understand this Error called "Buffer Overflow". My code is as follows:
#include <stdio.h>
int main()
{
char a[5];
gets(a);
printf ("%s",a);
return 0;
}
Now when I type more that 5 words it should end with five, shouldn't it? But its showing some buffer error and I have no idea what to do about it. please help me with this.
isn't that a[5] is the word limit of 5?
I'm very confused.
Sorry if it distrub you all and thanks in advance.
Actually, the limit is 4 characters, because a null terminator will be added to the end in order to form a valid string. This means that you need char a[6] if you want space for 5 characters.
Also, gets shouldn't be used for this exact reason. Instead, I would use scanf:
scanf("%5s", a);
This will tell it to read 5 characters at most, even if there are more.
With those changes, the program should look like this:
#include <stdio.h>
int main()
{
char a[6];
scanf("%5s", a);
printf ("%s",a);
return 0;
}
It's also possible to use fgets instead:
fgets(a, 5, stdin);
Related
Hey I am beginner in programming i need help to solve this problem
I want that i input some character and i want to print it..
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
return 0;
}
From the above code I am not getting any output i also try using loop but not get any result please help me what is correct program so that if i enter any string i print on the screen?
So here's your issue.
You are defining an array of type char with a length of 50. You then read from stdin a string, and then store it at the address of the 50th element. So what will happen is you are storing the string "out of bounds" and you may get a crash, or may not.
Either way, something very bad is happening. You are writing data to an area of memory that you should not be.
So what you want to do is write that data to the address of the 0th index of the array.
You do that by using &a[0] or, for simplicity's sake: a. Both mean the same thing.
At the end of the day, what you want is this:
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",a);
printf("You entered is %s",a);
return 0;
}
I understand you are a beginner and are learning basic concepts, but keep in mind, this code is very unsafe. Because if someone types in a length of characters longer than 50, you are back in the same boat you were before.
Quoting kaylum's comment, "It would be beneficial to go through a basic C book or tutorial before proceeding further."
Now about your issue, change these lines:
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
to
scanf("%50s", a);
printf("You entered \"%s\".\n", a);
If you just want to print what's inputted by the user then you could use buffer:
#include <stdio.h>
int main(void)
{
char c;
printf("Enter the string(~ to exit)\n");
while((c = getchar()) != '~')
putchar(c);
return 0;
}
Output:
Enter the string(~ to exit)
This is a test program // press enter
This is a test program // same output
~ // exit
The problem is about taking input of strings x number of times using an array of pointers. x is the value entered by the user. I wrote the following code for the same. But the program is taking only x-1 inputs.
I have inserted fflush(stdin) because I think the scanf is consuming an enter first but I don't know from where.
I have tried using gets but with no use.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
//code to take input in an array of pointers
int x,i,j,length;
char ch[50],*t;
printf("How many names you want to sort:\n");
scanf("%d",&x);
char *names[x];
char *p;
printf("Enter the names:\n");
for(i=0;i<x;i++)
{
fflush(stdin);
scanf("%[^\n]s",ch);
length = strlen(ch);
p = (char *)malloc((length+1) * sizeof(char));
strcpy(p,ch);
names[i] = p;
}
return 0;
}
Why bother with complex format strings if you don't have to? Use fgets.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void err(const char * msg) {
fprintf(stderr, msg);
exit(1);
}
int main()
{
int x,i;
char ch[50];
printf("How many names you want to sort:\n");
if(!fgets(ch, 50, stdin)) err("Error reading line");
if(sscanf(ch, "%d",&x) != 1) err("Could not read integer");
// Better than using VLA
char **names = malloc(x*sizeof(*names));
if(!names) err("Error allocating names");
printf("Enter the names:\n");
for(i=0;i<x;i++) {
if(!fgets(ch, 50, stdin)) err("Error reading line");
ch[strcspn(ch, "\n")] = 0; // Remove newline
if(!(names[i] = strdup(ch))) err("Error duplicating string");
}
for(int i=0; i<x; i++)
printf("name %d: %s\n", i, names[i]);
}
Whenever a function has a return value that may indicate an error you should ALWAYS check it, and here that is the case for malloc, fgets, strdup and sscanf and. Read the documentation to find out what it actually returns to see how to check for errors. sscanf returns the number of successful assignments, and the other three returns a pointer which is NULL on failure.
You wrote in the comments that you are learning from the book "Let us C". A better fitting title would be "How to not code C". I've had a quick look at it and, it is really really bad. Apart from teaching very outdated C, it also teaches very bad habits in general, and many of the things you can read is completely WRONG. Actually, the majority of questions about C can be traced to that book, or at least could have. Two prime examples is that it consistently avoids very important stuff, such as error checking functions like scanf and malloc. I have not read every line, but I think it does not even mention how to error check scanf even once. It also uses the function gets which is not only deprecated but completely removed from newer C standards because it is so dangerous. It also says that you can modify a string literal, which is undefined behavior in C.
#include <stdio.h>
int main(void) {
char str[100];
scanf("%s", str[0]);
printf("%c", str[1]);
return 0;
}
I am running this code. I have entered "Jagrit" as an input. I expect the output of above program is 'j'. But instead i get nothing as a output just a blank space. Can anyone tell me why is it so and what was the error in the code ?
scanf expects the address of memrory to write to read data to:
#include <stdio.h>
int main(void) {
char str[100];
scanf("%s", str);
printf("%c",str[0]);
return 0;
}
Have a look at the example section of this doc on scanf.
What was your intention with scanf("%s", "jargrit dolir") ?
This
scanf("%s","jagrit dolir");/*it doesn't put data into str, and doing that causes UB*/
So accessing str[0] may cause undefined behavior because str doesn't initialized & it's not having any data.
Instead use like below.
scanf("%s",str);/* now give input like jagrit dolir */
And then print str[0].
Edit :- since you modify the code. Have you read the manual page of scanf() ?
scanf("%s",str[0]);/* why you are not reading compiler warning here ?*/
Here %s expects argument of char* but you provided char type.
if you just want to take a input as a string can use fgets()
and just use str[0] to print the first character of the string
note that
printf() is used to print values only;
here is the simple version of the code:
#include <stdio.h>
# include<stdlib.h>
int main() {
char str[100];
fgets(str,100,stdin);
printf("%c",str[0]);
return 0;
}
when you use str[0] , you access it's value so the scanf should be like thit scanf("%s",&str[0]); or like this scanf("%s",str);
you also should expect the output to be 'a'
try this code
#include <stdio.h>
int main()
{
char str[100];
printf("%s","jagrit dolir");
printf("%c",str[0]);
return 0;
}
I'm running a while loop so the user can constantly enter expressions, until they indicate they want to quit the program. I'm using strcmp() to compare two strings so as soon as they enter quit the program will stop. But the program keeps going, any Ideas?
#include <stdio.h>
#include <string.h>
int main()
{
int min12=0;
char opper;
int x=0;
int min13;
char *Repeatprog="cont";
char *Repeatprog1="quit";
while (strcmp(Repeatprog,Repeatprog1))
{
printf("enter the integer number \n");
scanf( "%d %c %d", &min12, &opper, &min13);
printf("%d %c %d\n", min12, opper, min13);
printf("Type the word quit to end program\n");
scanf("%s", Repeatprog);
}
printf("Good Bye");
return 0;
}
Remember always that an Array is a Pointer to the first object of the array.
And secondly, in your call to scanf() you only read a character. Not a whole string (represented by %s in C)
So in conclusion, your call to scanf() shouldn't have a pointer and should have a string instead of a character.
scanf("%s", Repeatprog);
or simply
gets (Repeatprog);
EDIT :
As the commenter #EOF said, gets() is not a good idea since it can lead to Undefined Behaviour. That's because the program can read more characters than it should have and lead to overflow, thus it isn't secure.
So I recommend using char *fgets(char *str, int n, FILE *stream)
Note:
Also, your code is using string literals. So if you make any attempt to change the content of the char pointer then it will lead to Undefined Behaviour.
For this note, please thank the guys below me [comments]. I made a huge mistake and I'm sorry.
I need help on this exercise from C Primer Plus.
Write a program that requests your first name and does the following with it:
Prints it in a field three characters wider than the name
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
int p,v=0;
printf("Enter your first name: \n");
scanf("%s",a);
p= strlen(a);
v==p+3;
printf("%s",a);
}
I cant figure out how what to use as a modifier for the width
what should I add in between % and s?
the goal of this excercise is to read and grok the manual page for printf(). The reading part could only be done by you and there is no shortcut. The format specifier is the most complex chapter in C-Programing (other would say 'pointer'), and it is very wise to know where look things up (man-page) in need of remembering.
When you are done reading, you should have a little (or big) understanding of the format-specifier %s with all its possibilities.
EDITH: when you are done reading, and there is still a question whether to use "%*.*s" or "%s" or "%-.*s" etc., please come back with an updated question.
Here is one way to do it:
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
printf("Enter your first name: \n");
scanf("%s",a);
printf("[%-*s]", (int)(3 + strlen(a)), a);
return(0);
}
The printf() function can do it all.
From the question code, it is clear that "%s" as a format string is understood.
A format string of "%*s" allows the caller to place the (space-padded) width to be specified. For example:
printf("%*s", 10, "Hello");
The above will print "Hello" (as expected), in a 10-character frame. Hence, the command above actually prints: " Hello".
To put the spaces on the other side, tell printf() to left-justify the string using:
printf("%-*s", 10, "Hello");
This results in printing: "Hello "