I'm trying to make a word counter program and want to dynamically allocate memory for the string without extra space. Here's my code so far:
#include <stdio.h>
#include <stdlib.h>
char *strmalloc(char *string);
char *user_input = NULL;
int main(void) {
printf("Enter a sentence to find out the number of words: ");
strmalloc(user_input);
printf("You entered %s", user_input);
return 0;
}
char *strmalloc(char *string) {
char *tmp = NULL;
size_t size = 0, index = 0;
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
if (size <= index) {
size += 1;
tmp = realloc(string, size);
if (!tmp) {
free(string);
string = NULL;
break;
}
string = tmp;
}
string[index++] = ch;
}
return string;
}
Here's the output:
Enter a sentence to find out the number of words: Testing program
You entered (null)
Process finished with exit code 0
I thought that in the while loop, I reallocate 1 byte of memory until the string fits just right? What am I doing wrong?
In your functiuon:
char *strmalloc(char *string) {
===> char *strmalloc(char **string) {
tmp = realloc(string, size);
===> tmp = realloc(*string, size);
string = NULL;
===> *string = NULL;
string = tmp;
===> *string = tmp
;
string[index++] = ch;
===> (*string)[index++] = ch;
return string;
===> return *string;
In the calling function:
strmalloc(user_input);
===> strmalloc(&user_input);