Reputation: 25
I have this code sample, and generally understand its logic, but am stuck in some details.
#define LSH_RL_BUFSIZE 1024
char *lsh_read_line(void) {
int bufsize = LSH_RL_BUFSIZE;
int position = 0;
char *buffer = malloc(sizeof(char) * bufsize);
int c;
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
while (1) {
// Read a character
c = getchar();
// If we hit EOF, replace it with a null character and return.
if (c == EOF || c == '\n') {
buffer[position] = '\0';
return buffer;
} else {
buffer[position] = c;
}
position++;
// If we have exceeded the buffer, reallocate.
if (position >= bufsize) {
bufsize += LSH_RL_BUFSIZE;
buffer = realloc(buffer, bufsize);
if (!buffer) {
fprintf(stderr, "lsh: allocation error\n");
exit(EXIT_FAILURE);
}
}
}
}
I cannot understand two things: Firstly, what exactly does this line do?
char *buffer = malloc(sizeof(char) * bufsize)
And secondly, how does the following line work? How is it that a pointer can be returned?
return buffer;
Upvotes: 1
Views: 2442
Reputation: 51
what exactly does this line do?
malloc
means "memory allocation"
malloc
function is used to dynamically create a memory block, it allocates a memory block of size specified in bytes (as a parameter). It returns a pointer to the beginning of that block.
So the specified size here is 'sizeof(char) * bufsize
' i.e. a block of characters of length 'bufsize
' is being requested. To get a size of 1 character you use the operator sizeof (sizeof is an operator not a function)
how does the following line work?
the function lsh_read_line
returns pointer to a memory block, which is the memory allocated by malloc
here - and it is buffer
.
How is it that a pointer can be returned?
Since it is dynamic memory from the heap - it is valid memory block even after the function returns.
As a side note - 'lsh_read_line
' caller must free this buffer
otherwise there is a memory leak!
For further details on C Function stack please refer to https://en.wikipedia.org/wiki/Call_stack
Upvotes: 3