So I'm trying to create a dynamically allocated user input string. I thought I had everything figured out but theres seems to be a problem when my program reaches 16 char's. Any string smaller than 16 chars seems to work completely fine, and will print out on the screen. Once the string length goes beyond that printf displays garbage. I sat there for about 2 hours trying to figure out why but I can't seem to get it.
I even use printf(%s) RIGHT before the function exits and the string prints out completely fine.
Also, am I even going about this the right way?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
#include "lab4.h"
int main()
{
char *dynamic_string;
dynamic_string = (char *)malloc(sizeof(char));
if(dynamic_string == NULL)
{
printf("Error");
return 1;
}
user_input(dynamic_string);
printf("%s\n", dynamic_string);
return 0;
}
Code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
void user_input(char *input_array)
{
int i;
int j;
int flag = 0;
int string_size = 0;
int num_allocated = 1;
char * temp;
for(i=0; flag!=1; i++)
{
scanf("%c", &input_array[i]);
string_size++;
if(string_size == num_allocated)
{
temp = (char *)malloc(num_allocated*2);
if(temp == NULL)
{
printf("Error");
flag = 1;
}
for(j=0; j<=string_size; j++)
{
temp[j] = input_array[j];
}
free(input_array);
input_array = (char *)malloc(num_allocated*2);
if(input_array == NULL)
{
printf("Error");
flag = 1;
}
for(j=0; j<=string_size; j++)
{
input_array[j] = temp[j];
}
free(temp);
temp = NULL;
num_allocated *= 2;
}
if(input_array[i] == '\n')
{
input_array[i] = '\0';
printf("TEST = %s\n", input_array);
flag = 1;
}
}
}