#include <stdio.h>
#include <stdlib.h>
int main(void) {
int x;
int *in, *begin;
in = (int *)malloc(sizeof(int));
begin = in;
while ((x = getchar()) != EOF) {
*in = x;
in++;
in = (int *)malloc(sizeof(int));
}
*in = EOF;
while ((x = *begin) != EOF) {
putchar(x);
begin++;
}
free(in);
return 0;
}
I have a sneaking suspicion that it does.
With this program, I’m trying to store user input of an indefinite size into memory using pointers, as opposed to using char string[255]; fgets(string, sizeof(string)); etc.
EDIT: The program doesn’t crash or anything when I run it, I just have a feeling there’s memory getting allocated that isn’t getting freed.
Yes you have.
Freewill deallocate memory for one only integer. You have to callfreefor everymalloccall you have done.Also to store the characters in a continuous buffer you have to
mallocan amount of memory at the beginning and usereallocif the characters you read become more than those initially allocated memory for.Also don’t forget to allocate one more character for the
\0at the end of the string.When you are done you can call
free(buffer)and… Success! No memory leaks!And the code for it: