What if user enters 1000000 bytes from his/her keyboard?Code:
#include <stdio.h>
int main (void)
{
char *str;
fgets (str, 1000000, stdin);
return 0;
}
Is there any allocated memory to place them?
Thanks
Printable View
What if user enters 1000000 bytes from his/her keyboard?Code:
#include <stdio.h>
int main (void)
{
char *str;
fgets (str, 1000000, stdin);
return 0;
}
Is there any allocated memory to place them?
Thanks
No there is not - you'll have to use malloc to allocate the 1000000 bytes.
But program works without allocating memory ? !
It may work this time - and even next time, but I guarentee you that it will eventually fail. What you have is an unitialised pointer, which could be pointing anywhere in memory - then you write the user input at this location in memory.
If you are entering only a couple of chars you will probably get away with it, but eventually your program will attempt to overwrite memory that doesn't belong to it. If you allocate the memory and the allocation succeeds, then you may write data at this location.
PS: I thought 1000000 was a bit of overkill (pretty long string :) ) so I went for something smaller.Code:#include <stdio.h>
#include <stdlib.h>
int main (void)
{
char *str;
if((str = (char *) malloc(sizeof(char) * 101)) == NULL)
{
printf("Error: Unable to allocate memory");
exit(1);
}
fgets (str, 100, stdin);
return 0;
}
Thank you, foniks !
No problem, but I made a really bad mistake..
free(str);
Once your finished with the memory that you have borrowed from the system, you must return it! :)
Ok ok.
I'm new to all this mumbo jumbo - what if I want to read an arbitrarily long string? As in - there is not limit to how long it is (within a theoretical limit)... no max_length definitions, etc.
how would I go about doing that? I've been trying it myself, and looking around the place, but to no avail.
cheers! :cool: