fprintf gives unexpected output while sending it to file [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char name[50];
int main()
{
FILE *fp;
fp = fopen("./account.txt","a+");
memset(name,'-',50);
scanf("%s",name);
printf("%s",name); // i get correctoutput
fprintf(fp,"%s",name); // I get wrong output
return 0;
}
In my code I have
-- global declaration
char name[50];
and in main I use
memset(name,'-',49);
and read the value into the string using scanf. I am getting two different output's
//assume I give the input as test
If I use printf to print the char array onto the monitor I get proper output as test
If i use fprintf and print the char array onto file I get wrong output,
like first 49 characters as '-' followed by a 0 then whatever I type (In this case test)
-------------------------------------------------0test
Can someone explain what's happening ? Or how to tackle such problems ?

char name[50];
...
int main()
{
memset(name, '-', 50);
}
Strings in C are characters which are contiguous in memory, followed by a NULL character ('\0') to mark the end of the string. When printing a string, printf will print each character in the string until it encounters the NULL byte, then stop.
In this case, the whole string starts off as NULL characters (because it's an un-initialised global), then you overwrite all of the string with '-'. By doing so, there is no longer a NULL terminator to mark the end of the string.
We're now into the land of undefined behaviour. The printf call worked because it just so happened that the next bit of storage was a zero in that case, but such behaviour must not be relied upon (again...undefined behaviour).
To fix this, you need to add the null terminator manually, for example:
char name[50];
int main()
{
memset(name, '-', 49); // Note we're not writing to the last byte now!
name[49] = '\0';
}

Related

fopen() crashing on second use in c [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
for some reason, fopens keeps crashing in my program.
It works once when I am reading the input file and putting the contents into a variable. But for some reason, when I try to make it use fopens again, it crashes...
Could someone please help
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *buf = "\0";
char buffer[99999] ;
int main(int argc, char *argv[])
{
ptr_file =fopen(inputFileLocation,"r");
if (!ptr_file)
{
return 1;
}
while (fgets(buf,maxvalue, ptr_file)!=NULL)
{
strcat(buffer,buf);
}
fclose(ptr_file);
... //workings
//then the program crashes if I add an fopen() and fclose() at the end
}
The accepted answer misses the point. It is not only about buffer overrun.
There is no buffer overrun for maxvalue = 2; yet the program will crash.
But step by step:
fgets(buf, maxvalue, ptr_file) != NULL
The C library function char *fgets(char *str, int n, FILE *stream)
reads a line from the specified stream and stores it into the string
pointed to by str. It stops when either (n-1) characters are read,
the newline character is read, or the end-of-file is reached,
whichever comes first. A null character is automatically appended in
str after the characters read to signal the end of the C string.
In your case buf is string literal of size 2. This is quite likely too small for your needs.
But its not just about the size of buf!
You cannot copy anything to the (constant) string literal! That operation crashes your program with signal 11 even if you read one character.
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals.
What you need is a char array of the proper size.
You could either declare it the same way as char buffer[99999]
// 1.
char buf[SIZE_OF_THE_BUF]; // remember that buf has to accept maxvalue-1 characters + `null` character
or dynamically allocate memory for it in the main()
// 2.a
char *buf;
//
int main()
{
// 2.b
buf = malloc(maxvalue * sizeof(char));
//...
}
You create a pointer named buf that points to space containing a single character '\0'.
Then you use fgets() to try to read an unknown number of characters (you don't show what maxvalue is) into the space pointed to by buf. But that space is only one character long. Reading into it will overrun the space, causing undefined behavior.

please tell me why does the output of the two picture is different? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This program accept 5 string and print them.
here is the program:-
#include"stdio.h"
#include"conio.h"
void main(){
clrscr();
char s[5];
for(int i=0;i<5;i++){
scanf("%s", s[i]);
}
for(i=0;i<5;i++){
printf("\n\n%s", s[i]);
}
getch();
}
when i execute this program the output will be this
Click here to see the output of the program
but when i enter the string in different way it print wrong output
Click here to see the output of the program
You are reading a string into a char, or rather, the string you read starts at the char position i in s. As s is very short (and when i is 5 it is empty), there will be an overflow, causing undefined behavior.
You want to have an array of strings, not of chars, as Blue Pixy mentions in his comment, e.g. char s[5][32];.
Also turn warnings on. The i in the second for loop is not defined.
You've declared s as a 5-element array of char; each s[i] can store a single character value, not a string. Since you don't explicitly initialize each s[i], they contain an indeterminate value.
The argument corresponding to the %s specifier in scanf must have type char * (each s[i] has type char), and it must point to the first element of an array of char large enough to store the string contents (including the 0 terminator that marks the end of the string).
When you call
scanf( "%s", s[i] );
you're telling scanf to store the next sequence of non-whitespace characters to the address corresponding to the value stored in s[i], which is a) indeterminate and b) likely not valid. The resulting behavior is undefined, meaning pretty much anything can happen - your code may work as expected, it may crash outright, it may give you garbled output, it may corrupt other data, etc.
As written, s can store a string up to 4 characters long.
If you want to store an array of strings, then s needs to be a 2-dimensional array of char:
#define MAX_STRING_LENGTH 20 // or however long you expect your longest string to be
...
char s[5][MAX_STRING_LENGTH + 1];
Each s[i] can now store a string up to MAX_STRING_LENGTH characters. The rest of your code should now behave as expected.

Inputting an arithmatic statement in c and return the value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
(I am very bad at inputting/processing strings in C. Hope this question will teach me a lot.)
I am trying to make a function that will input an arithmatic string from stdin, e.g 23 + 45 * 6 - 5, and return the value.
There are multiple strings, entered one after another, and can be of any length and the operator precedence doesn't matter, i.e., it processes string sequentially.
The problems that I faced are :-
\n from previous string is also considered a string.So if I input 3 strings , it will actually be 6, 3 strings and 3 \n.
I used a char pointer and used char * input; scanf(" %s",input);, but in addition to above problem, I also get segmentation fault, which I guess is due to missing \0.
My question is forget what mess I did, what would you have done or what's the best way to handle string input in the above scenario. A dummy code is sufficient.Thanks.
What I was doing
#include <stdio.h>
int main()
{
int t; //no of test cases
char input;
scanf("%d",&t);
while(t--)
{
while((input=getchar())!='\n')
{
//use switch to identify char and follow appropriate action
printf("%c\n",input );
}
}
return 0;
}
As suggested by Joachim Pileborg, use fgets. Use a char array, instead of one char variable, to store the string.
char input[100];
fgets(input, sizeof(input), stdin);
The advantage of fgets over sscanf is that fgets can read spaces in your input.
It will include the end-of-line byte \n, so 3 strings will not turn into 6 strings.
As usual with fgets, there is an arbitrary limit on the length of the input. If the user inputs something longer than 98 bytes, the system cannot fit it all (plus end-of-line \n and end-of-string \0 bytes), and the program will receive truncated string.
If you cannot tolerate that, use getline (it's harder to use, so use fgets if in doubt).
After you scan your string in, check to see if it is a '\n', if it is just ignore processing it and move to the next one.
Or you could try:
char input[101];
scanf("%s\n", &input);
First of all. Your idea of writing an fomular expression analyzer as a first projekt is not a very good one. Start with a simpler project.
You get the sagmentation fault, because you try to read data (with the scanf()) into a not initialized pointer.
char *input;
will not allocate any memory for the string you want to read with scanf(). You have to use a buffer something like
char input[256];
and give the pointer to the buffer to scanf("%s",input) (oder for better understanding scanf("%s",&input[0]);
Anywhere, this buffer has only 255 chars to store and you must be aware, that if you enter more then 255 chars in the scanf() you will get an illegal memory access as well.
Claus

I am trying to do a program that picks a vowel from the user input [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *v= "a";
char *o='e';
char * w='i';
char *e='o';
char *l='u';
char *u[1];
printf ("please enter your character\n");
scanf ("%c",& u);
if (u == v){
puts("the character is it a vowel\n");
}
if (u == o) {
puts("the character is it a vowel\n");
}
else
puts("the character is a constant\n");
system("PAUSE");
return 0;
}
i need help in getting the right answer in finding a vowel from the user input.
First of all, shame on you for ignoring all of the compiler warnings you certainly received. They are there to help prevent you from doing "stupid things."
And why all this nonsense? This is the first of the "stupid things" the compiler is trying to tell you about.
char *v= "a";
char *o='e'; // invalid - Initializing a pointer to a constant 'e' (101).
char * w='i'; // invalid
char *e='o'; // invalid
char *l='u'; // invalid
Are you familiar with how pointers work? If not, I suggest you do some reading and understand them.
The first line makes sense - you're making a string and pointing char* v to that string.
But there's really no point in using pointer for those characters - or even variables at all. Just compare them directly:
char my_character;
if (my_character == 'a') {
// do something
}
And as for reading the character, again, you're using pointers when it doesn't make sense:
char *u[1]; // why?
Instead, just define a single char variable. Now, go look at the documentation for scanf. Giving it a format string of "%c" means, "I want to read just one character". Then, you need to tell where scanf to put it. You do this by passing it the "address of" the variable you want to store it in. You do this with (unsurprisingly!) the address of operator &.
char input_character;
scanf("%c", &input_character);
Armed with this information, you should be able to complete your work. Next, I suggest you look into the switch statement.
Finally, you must use consistent formatting (indentation, spacing) and use meaningful variable names, if you have any desire of ever being taken seriously as a programmer. Spelling out "vowel" for your pointless variables may be "cute" but it's total nonsense.
Most importantly, you should never write a single line of code, unless you understand exactly what it does. If you do this, then do not go asking anyone for help (especially not StackOverflow). If you can't explain what your code is doing (or at least what you think it's supposed to do), then you don't deserve for your program to work.

Arrays Stack Overflow [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
#include
int main(void)
{
char str[100]="88888888888888";
char t[20]="";
gets(t);
puts(str);
puts(t);
return 0;
}
The first line
555555555555555555555555555555555
is put in.
Why str is 55555555555? Why str isn't 88888888888888888 or 55555555555588888?
You overriden the t buffer, and reached the str buffer, where the rest of the input, and the null terminator was set. And puts prints only until the null terminator.
Pretty much looks like that:
[ t (20) ][str(100) ]
55555555555555555555 5555555555555\0
Note that although t is declared as char[20], when you print it you get the full input (longer than 20), since puts stops at the null terminator (again).
BTW, this is a buffer overflow, not a stackoverflow, but stack overflow is possible on this codeas well.
As Binyamin said it is caused by the overflow you trigger because of the input string being too long. However it is a bit random thing - sometimes the two memory allocations will happen just next to each other and the string will extend to the neighbouring variables, sometimes it might not happen.
I advise you to place guard conditions for such kind of overflows.
If you see in the gets documentation:
Notice that gets does not behave exactly as fgets does with stdin as
argument: First, the ending newline character is not included with
gets while with fgets it is. And second, gets does not let you specify
a limit on how many characters are to be read, so you must be careful
with the size of the array pointed by str to avoid buffer overflows.
In your case if you do not know the size apriory maybe it is better idea to use fgets as it is more secure (though a bit slower).
When you enter a string of more than 20 5s, it overruns the buffer that was allocated to t and extends into the buffer that was allocated to str.
Then it displays the contents of str, which is the string you entered, starting at the 21st character.
Finally, it displays the contents of t, but since that string doesn't end with a null character, it continues displaying memory (which is the buffer assiged to str) until it encounters the null character after all the 5s.
In order to avoid those allocation overlapping issues you can try this alternative, so that the allocation takes place at runtime if I'm not wrong:
#include <iostream>
int main(void)
{
char *str;
char *t;
str = new char(100);
str = (char*)"88888888888888";
t = new char(20);
std::cin >> t;
puts(str);
puts(t);
return 0;
}

Resources