It’s quite simple, as long as you pass to free()
the same pointer returned by malloc()
it’s fine.
For example
char *readInput(size_t size)
{
char *input;
int chr;
input = malloc(size + 1);
if (input == NULL)
return NULL;
while ((i < size) && ((chr = getchar()) != '\n') && (chr != EOF))
input[i++] = chr;
input[size] = '\0'; /* nul terminate the array, so it can be a string */
return input;
}
int main(void)
{
char *input;
input = readInput(100);
if (input == NULL)
return -1;
printf("input: %s\n", input);
/* now you can free it */
free(input);
return 0;
}
What you should never do is something like
free(input + n);
because input + n
is not the pointer return by malloc()
.
But your code, has other issues you should take care of
-
You are allocating space for
MAX_SIZE
char
s so you should multiply bysizeof(char)
which is1
, instead ofsizeof(char *)
which would allocateMAX_SIZE
pointers, and also you could makeMAX_SIZE
a function parameter instead, because if you are allocating a fixed buffer, you could define an array inmain()
with sizeMAX_SIZE
likechar input[MAX_SIZE]
, and pass it toreadInput()
as a parameter, thus avoidingmalloc()
andfree()
. -
You are allocating that much space but you don’t prevent overflow in your
while
loop, you should verify thati < MAX_SIZE
.