I am trying to take a string input in C and I have tried both scanf
and fgets
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 fgets
and scanf
. 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
qwertyuiolkjhgfdsazxcvbnmSTACK
OVERFLOW
- qwertyuiolkjhgfdOVERFLOW <<<<<< The second string gets appended in the first
- 25
- OVERFLOW
- 9