如何从另一个文件中释放内存?
How to free memory from another file?
我正在学习动态内存分配。
我写了几行来理解指针、表和内存分配是如何工作的。我有一个 malloc
函数,但我不知道把 free
函数放在哪里?
main.c :
#include <stdio.h>
#include <stdlib.h>
#include "allocation.c"
int main(void)
{
int count = 5;
int initValue = 2;
int increment = 3;
int *result = arithmeticSequence(count, initValue, increment);
printf("Adresse de mon pointeur : %p\n", result);
for(int i=0 ; i < count ; i++)
{
printf("[%d]", *result);
result++;
}
return 0;
}
allocation.c :
#include <stdlib.h>
#include "allocation.h"
int *arithmeticSequence(int count, int initValue, int increment)
{
int *table = NULL;
table = malloc(count * sizeof(int));
if(table == NULL)
exit(1);
for(int i=0 ; i < count ; i++)
{
table[i] = initValue + i * increment;
}
printf("Adresse de l'element 0 de la table : %p\n", &table[0]);
return &table[0];
}
这是对象所有权的问题。任何函数(或 class、模块等) 拥有 对象(或指针)负责确保它在所有可能的条件下被释放(或销毁),因为不再需要后尽快。确保除了所有者之外没有其他人释放它也很重要。
作为程序员,您需要决定每个指针的最佳“所有者”是什么。在这个程序中,最好的选择是main
函数。
我正在学习动态内存分配。
我写了几行来理解指针、表和内存分配是如何工作的。我有一个 malloc
函数,但我不知道把 free
函数放在哪里?
main.c :
#include <stdio.h>
#include <stdlib.h>
#include "allocation.c"
int main(void)
{
int count = 5;
int initValue = 2;
int increment = 3;
int *result = arithmeticSequence(count, initValue, increment);
printf("Adresse de mon pointeur : %p\n", result);
for(int i=0 ; i < count ; i++)
{
printf("[%d]", *result);
result++;
}
return 0;
}
allocation.c :
#include <stdlib.h>
#include "allocation.h"
int *arithmeticSequence(int count, int initValue, int increment)
{
int *table = NULL;
table = malloc(count * sizeof(int));
if(table == NULL)
exit(1);
for(int i=0 ; i < count ; i++)
{
table[i] = initValue + i * increment;
}
printf("Adresse de l'element 0 de la table : %p\n", &table[0]);
return &table[0];
}
这是对象所有权的问题。任何函数(或 class、模块等) 拥有 对象(或指针)负责确保它在所有可能的条件下被释放(或销毁),因为不再需要后尽快。确保除了所有者之外没有其他人释放它也很重要。
作为程序员,您需要决定每个指针的最佳“所有者”是什么。在这个程序中,最好的选择是main
函数。