First post here, apologies in advance for any blasphemous/offensive breaches of posting etiquette.
In a nutshell, I would like a fool proof and efficient method of obtaining a string from the user and or file-streams.
Ideally, I'd like to be able to allocate an array of characters - and have the right amount for that string. I believe this is achievable using the "malloc" function, but as yet can't get my head around the concept. I understand what it does, just now how to implement it.
Below is a small program I wrote to experiment with the various ways of getting input from "stdin".
Code:
/* input.c
Various methods of getting input from the user */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char sbuf[3], buf[80], *message;
/* Input a string. */
puts("Enter 1st line of text. To be placed in small buffer.");
gets(sbuf);
puts(sbuf);
printf("%d \n", strlen(sbuf));
/* Input a string. */
puts("Enter 2nd line of text. To be placed in big buffer.");
gets(buf);
puts(buf);
/* Input a string. */
puts("Enter 3rd line of text. Dynamically allocated spave");
gets(buf);
puts(buf);
/* Allocate the initial block and copy the string to it. */
message = realloc(NULL, strlen(buf)+1);
strcpy(message, buf);
puts(buf);
/* Input a string. */
puts("Enter 3rd line of text. Fgets, 4 char buffer");
fgets(buf, 4, stdin);
puts(buf);
getch();
return 0;
}
The above code was compiled, successfully, in Dev-C++ 4.9.9.2 running on Windows XP Home Edition
All 4 methods work. As in I can display the array in the terminal, and have no 'junk' characters appear, or lose any of the message I typed in - however long.
Here is where it all goes pair shaped.
I set aside 3 characters as a "small buffer", and called is sbuf. Using the "gets" function; if I type more than 3 characters I can still display the entire message.
Where are my "extra" characters being stored?
Is this some delightful feature of my compiler, protecting the programmer from himself?
I have no idea what is going on here.
I hope someone here can shed some light on this. I'd like a solution, but also to understand the solution.
Thanks in advance,
Clint