molecule molecule - 9 months ago 48
C Question

The second input replaces the last characters of the first input in scanf and fgets

I am trying to take a string input in C and I have tried both

for the same. However, one weird thing that is happening is that when I take a large input in first string, and then press enter and enter the second string, the second string replaces the characters at the end of the first string. This is happening with both
. What am I doing wrong ?

Here is the code

#include <stdio.h>
#include <stdlib.h>
#include <string>

#define MAX_SIZE 10000 // Added in the edit

int main() {
char* str1;
char* str2;
char* deleted;
int len1, len2;

str1 = (char*)(malloc(sizeof(MAX_SIZE)));
str2 = (char*)(malloc(sizeof(MAX_SIZE)));
deleted = (char*)(malloc(sizeof(MAX_SIZE)));

fgets (str1, MAX_SIZE, stdin);
fgets (str2, MAX_SIZE, stdin);

printf(" - %s - %d \n", str1, len1);
printf(" - %s - %d \n", str2, len2);

Here is the output :

$ ./a.out
- qwertyuiolkjhgfdOVERFLOW <<<<<< The second string gets appended in the first
- 25
- 9

Answer Source

Given #define MAX_SIZE 10000


str1 = (char*)(malloc(sizeof(MAX_SIZE))); // <-- wrong

What you need is:

str1 = malloc(MAX_SIZE * sizeof(char));

Also, you have deleted variable that is never used.

And remember fgets has \n at the end that is usually removed by using strcspn (Removing trailing newline character from fgets() input)

str1[strcspn(str1, "\n")] = 0;

Finally, you are using len1, len2 completely uninitialised, this caused undefined behaviour. What you need is:

printf(" - %s - %zu \n", str1, strlen(str1));