我有这个代码示例,大致理解它的逻辑,但在一些细节上卡住了。
#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);
}
}
}
}
我不明白两件事:首先,这条线到底是做什么的?
char *buffer = malloc(sizeof(char) * bufsize)
其次,下面一行是如何工作的?怎么返回一个指针?
return buffer;
最佳答案
what exactly does this line do?
malloc
表示“内存分配”
malloc
函数用于动态创建内存块,它分配一个以字节为单位指定大小的内存块(作为参数)。它返回指向该 block 开头的指针。
所以这里指定的大小是“sizeof(char) * bufsize
”,即正在请求长度为“bufsize
”的字符 block 。要获得 1 个字符的大小,您可以使用运算符 sizeof(sizeof 是运算符而不是函数)
how does the following line work?
lsh_read_line
函数返回指向内存块的指针,这里是malloc
分配的内存 - 它是buffer
。
How is it that a pointer can be returned?
因为它是来自堆的动态内存 - 即使在函数返回后它也是有效的内存块。
作为旁注 - 'lsh_read_line
' 调用者必须释放此 buffer
否则会发生内存泄漏!
有关C 函数堆栈 的更多详细信息,请参阅https://en.wikipedia.org/wiki/Call_stack
关于c - C 中的 Malloc - 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40518113/