了解内存分配的C代码示例 [英] Understanding C code example with memory allocation

查看:89
本文介绍了了解内存分配的C代码示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C的新手,我正在阅读K& R的The C Programming Language来学习它。我对第2版第109页上出现的这个示例函数有疑问:

I'm new to C and I'm reading "The C Programming Language" by K&R to learn it. I had a question about this example function appearing on pg 109 of the 2nd edition:

/* readlines:  read input lines */
int readlines(char *lineptr[], int maxlines)
{
   int len, nlines;
   char *p, line[MAXLEN];
   nlines = 0;
   while ((len = getline(line, MAXLEN)) > 0)
       if (nlines >= maxlines || p = alloc(len) == NULL)
           return -1;
       else {
           line[len-1] = '\0';  /* delete newline */
           strcpy(p, line);
           lineptr[nlines++] = p;
       }
   return nlines;
}

我想知道为什么 * p 在这里是必要的吗? p 分配内存,然后将复制到其中。为什么不能只使用 line ,所以最后 lineptr [nlines ++] = p 可以替换为 lineptr [nlines ++] = line

I was wondering why *p is at all necessary here? p is allocated memory and then line is copied into it. Why can't just line be used, so at the end lineptr[nlines++] = p could be replaced by lineptr[nlines++] = line.

推荐答案

如果你不分配对于每一行的内存,你最终会得到 lineptr 这是一个充满指向你读到的最后一行的指针的数组(更不用说堆栈内存可能是覆盖)。在读取时为每一行分配内存会使返回的数组有意义。举个例子,假设恰好在地址0x1000的堆栈上分配。如果您进行了建议的更改,则8行文件的结果 lineptr 数组将为:

If you don't allocate memory for each line, you'll end up with lineptr being an array full of pointers to just the last line you read (not to mention to stack memory which is likely to be overwritten). Allocating memory for each line as you read makes the returned array make sense. As an example, let's say that line happens to get allocated on the stack at address 0x1000. If you make your suggested change, the resulting lineptr array for an 8 line file would be:

0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000, 0x1000

Yowch!在读取每行时为每行分配内存,然后将行复制到分配的内存中是唯一的解决方案。

Yowch! Allocating memory for each line as you read it, and then copying the line into that allocated memory is the only solution.

这篇关于了解内存分配的C代码示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆