It's kinda heard to explain... i'll give an example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int len;
char* str_input;
printf("Enter len of str: ");
scanf("%d", &len);
str_input = (char*) malloc(len * sizeof(char));
printf("Enter str. & to end: ");
scanf("%s", str_input);
printf("%s", str_input);
}
The above code asks me to enter a length. Suppose I enter 1. then I allocate a memory of 1 byte. Then it asks me for a string. I enter something with length more than 1, for example "hello". And print it. And it prints the entire string "hello"!. Why does this happen? should the program crash because there isn't enough memory?
How do I fix this?