I have the following code that I am using to get a string from the user via a terminal prompt:
#include <stdio.h>
#include <stdlib.h>
void GetString(int*, int*);
int main(void)
{
unsigned int strLength = 32;
char *stringPtr = malloc(strLength);
printf("Enter some input: ");
if (stringPtr != NULL)
{
int c = EOF;
unsigned int i = 0;
while ((c = getchar()) != '\n' && c != EOF)
{
stringPtr[i++] = (char) c;
if (i == strLength)
{
strLength = i+strLength;
if(stringPtr = realloc(stringPtr, strLength))
}
}
stringPtr[i] = '\0';
printf("\n\nString value: %s\n\n", stringPtr);
free(stringPtr);
stringPtr = NULL;
}
}
It works well from a user perspective, however, I am rather novice and just now am truly starting to understand how pointers can work with one-another, however, I have yet to find a good working example online that can simplistically relay how to successfully handle an unknown amount of input without fear of buffer overflow, segmentation faults, etc.
The code that I listed above was built by me using pieces of several examples relating to dynamic memory allocation as well as some forums on string operations. Can anyone verify that this is a safe, efficient way to handle user input of unknown length? If not, could you provide information on why what I posted is incorrect and how it could be improved? I just want to ensure I am learning correctly, as I am teaching myself (for the most part) which can lead to very destructive misunderstandings when it comes to C, from what I have heard from friends/online articles.
*****I've modified the above code to a better state based on the help provided in the comments and answers below. I am open to further improvement on this and hope that this example can help others who are trying to better understand how to handle user input in a safe and efficient manner.******
#include <stdio.h>
#include <stdlib.h>
void GetString(int*, int*);
int main(void)
{
unsigned int strLength = 32;
char *stringPtr = malloc(strLength);
if (stringPtr == NULL)
{
fprintf(stderr, "Unable to allocate memory to hold char array. Exiting!\n");
return 1;
}
printf("Enter some input: ");
int c = EOF;
unsigned int i = 0;
while ((c = getchar()) != '\n' && c != EOF)
{
stringPtr[i++] = (char) c;
if (i == strLength)
{
strLength += strLength;
if ((stringPtr = realloc(stringPtr, strLength)) == NULL)
{
fprintf(stderr, "Unable to expand memory to hold char array. Exiting!\n");
return 2;
}
}
}
stringPtr[i] = '\0';
if (sizeof(stringPtr) < strLength)
{
stringPtr = realloc(stringPtr, strLength);
}
printf("\n\nString value: %s\n\n\n", stringPtr);
free(stringPtr);
stringPtr = NULL;
}