我是否在此 C 程序中正确释放内存?
Am I freeing memory properly in this C program?
我正在编写一个从用户读取多行输入的小程序:
#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
工作正常。
看来有个动态内存的概念我不是很了解。为什么会发生这种情况,在此特定程序中处理内存的正确方法是什么?
问题是您正在通过 运行 buffer++
修改缓冲区指针,因此当您调用 free(buffer)
时,您传递了错误的指针。您可以重写循环以不修改该指针。
我正在编写一个从用户读取多行输入的小程序:
#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
工作正常。
看来有个动态内存的概念我不是很了解。为什么会发生这种情况,在此特定程序中处理内存的正确方法是什么?
问题是您正在通过 运行 buffer++
修改缓冲区指针,因此当您调用 free(buffer)
时,您传递了错误的指针。您可以重写循环以不修改该指针。