-
Problem with code
I am writing a program that takes in a string of arbituary size. The only problem is that when it echos the text, all of the characters are smiley faces:
Mike
:) :) :) :)
here is the code:
#include <stdio.h>
#include <stdlib.h>
void read_string(void)
{
char current_char;
char *usr_data;
int stored_chars = -1;
int needed_chars = 128;
usr_data = malloc(128);
printf("Please enter some text to be echoed\n");
while (current_char = fgetc(stdin) != 10)
{
stored_chars++;
if (stored_chars > needed_chars - 1)
{
needed_chars *= 2;
usr_data = realloc(usr_data, needed_chars);
}
usr_data[stored_chars] = current_char;
}
if (stored_chars == needed_chars)
realloc(usr_data, needed_chars+1);
stored_chars++;
usr_data[stored_chars] = 0;
printf("%s\n", usr_data);
}
void main(void)
{
read_string();
}
-
STUPID FORUM ***!!!!
Anyway I fixed up your code. You had a pretty big memory leak. Dont forget to free up your memory allocation.
PHP Code:
#include <stdio.h>
#include <stdlib.h>
void read_string(void)
{
char current_char;
char *usr_data;
int stored_chars = -1;
int needed_chars = 128;
usr_data = (char*) malloc(128); //<<<----------- I am not sure if you need to do this or not
printf("Please enter some text to be echoed\n");
while ((current_char = (char) fgetc(stdin)) != 10) //<<<----------- Changed
{
stored_chars++;
if (stored_chars > needed_chars - 1)
{
needed_chars *= 2;
usr_data = (char*) realloc(usr_data, needed_chars); //<<<----------- I am not sure if you need to do this or not
}
usr_data[stored_chars] = current_char;
}
if (stored_chars == needed_chars)
realloc(usr_data, needed_chars+1);
stored_chars++;
usr_data[stored_chars] = '\0'; //<<<----------- There should be a \\0 but the code tags are removing it
printf("%s\n", usr_data);
free(usr_data); //<<<----------- Do NOT forget to free up the memory you use on a alloc
}
void main(void)
{
read_string();
}