【发布时间】:2015-06-18 04:42:55
【问题描述】:
我正在编写一个从用户那里读取多行输入的小程序:
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 256
#define MAXLINES 32
/* Reads at most maxLines inputs from stdin. Returns number of lines. */
int readlines(char** buffer, int maxLines, size_t maxInput);
/* Gets input from stdin with maxInput as the limit. Returns size of string. Terminates at newline. */
int getstdline(char* buffer, int maxInput);
int main(int argc, char** argv) {
char** buffer = malloc((sizeof buffer[0]) * MAXLINES);
int numlines = readlines(buffer, MAXLINES, MAXINPUT);
/* free memory that was allocated for each str */
for(int i = 0; i < numlines; ++i) {
free(*(buffer++));
}
/* free memory that was allocated to hold all the strings */
free(buffer);
}
int readlines(char** buffer, int maxLines, size_t maxInput) {
int linecount = 0;
while(maxLines--) {
char* tmp = malloc(maxInput);
/* if empty string, exit loop */
if(getstdline(tmp, maxInput) <= 0) {
free(tmp);
break;
}
*buffer = tmp;
++linecount;
++buffer;
}
return linecount;
}
我的问题是关于在readlines(char**,int,size_t) 中对malloc() 的调用。我显然不能free() 函数内的内存,所以要在程序结束时释放它,我尝试循环遍历char* 的数组并单独释放它们。然后我还在main() 中释放char** buffer,因为它也是使用malloc() 分配的。
遍历它们中的每一个都会给我错误:
object was probably modified after being freed.
最后释放char** buffer工作正常。
所以似乎有一个我不太了解的动态内存概念。为什么会发生这种情况?在这个特定程序中处理内存的正确方法是什么?
【问题讨论】:
-
char** buffer = malloc(MAXLINES);应该是char** buffer = malloc(MAXLINES * sizeof buffer[0]);。可怜的malloc()看不懂你的心思。 -
@TheParamagneticCroissant 哎呀!修好了。
-
@TheParamagneticCroissant 我猜这不应该是解决办法。问题依然存在。
-
这是问题之一。 “修复”正在这样做和答案建议。这也是一个问题,没有我的评论也无法正常工作。
标签: c malloc free dynamic-memory-allocation