如何释放 C++/C 格式的内存?我什么时候会写自由(a);?函数是重新指针
How can i free memory in C++/C? When would i write free(a);? Function is returing pointer
代码:
#include<cstdio>
#include<cstdlib>
#include<string>
#include<iostream>
using namespace std;
class KMP {
public:
int * prefix_array(string);
bool kmp_search(string,string,int *);
};
int * KMP::prefix_array(string pattern) {
int m,q,k;
int *a;
string p;
p=pattern;
m = p.length();
a = (int*)malloc(sizeof(int)*m);
a[0] = -1;
k=-1;
for(q=1;q<m;q++) {
while(k>-1 && p[k+1] != p[q]) {
k=a[k];
}
if(p[k+1]==p[q]) {
k=k+1;
}
a[q]=k;
}
/*
for(int i=0;i<m;i++) {
printf("%d ",a[i]);
}
printf("n");
*/
return a;
}
bool KMP::kmp_search(string str, string pattern,int *a) {
int n,m,q,i;
string S,p;
S = str;
p = pattern;
n = str.length();
m = pattern.length();
q = -1;
for(i=0;i<n;i++) {
while(q>-1 && p[q+1] != S[i]) {
q=a[q];
}
if(p[q+1] == S[i]) {
q=q+1;
}
if(q==m-1) {
q=a[q];
return true;
}
}
return false;
}
int main() {
//freopen("in.txt","r",stdin);
int testCase,num;
char ch;
string str,pattern;
char str2[250];
bool check;
int *arr;
KMP *obj = new KMP();
scanf("%dn",&testCase);
while(testCase--) {
getline(cin,str);
//cout<<str<<endl;
scanf("%dn",&num);
//printf("%dn",num);
while(num--) {
getline(cin,pattern);
arr=obj->prefix_array(pattern);
check = obj->kmp_search(str,pattern,arr);
if(check) {
printf("yn");
} else {
printf("nn");
}
}
}
delete obj;
return 0;
}
输入.txt(输入):
2
abcdefghABCDEFGH
3
ababaca
abc
abAB
xyz
1
xyz
我正在尝试释放int * KMP::prefix_array(string pattern) {
中的内存.它通过以下方式分配内存:a = (int*)malloc(sizeof(int)*m);
,此函数返回指针。那么我怎样才能释放内存呢?
任何答案将不胜感激。提前谢谢。
返回已分配指针的函数意味着该内存的所有权正在转移给该函数的调用方。由接收返回指针的代码来释放内存。
虽然在C++中使用malloc()
和free()
并非完全没有先例,但通常应避免使用。您可以通过将代码更改为使用 std::vector<int>
而不是 int *
来完全避免此问题。
相关文章:
- 将自由函数绑定为类成员函数
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 为什么成员函数地址离自由函数这么远?
- 如何使用模板元编程在自由函数C++链接两个不相关的类
- C++ 20 中的运算符 == 和 <=> 应该作为成员还是自由函数实现?
- 如何在共享库中保留静态库中的自由函数
- 在C++项目中管理自由函数有哪些好的做法?
- 使用自由函数作为LPOVELAPPED_COMPLETION_ROUTINE
- 统一检查成员函数、自由函数和算子是否存在的方式
- 使自由函数的行为类似于成员函数 (C++)
- C++自由函数可以别名吗?
- 调用成员函数(如果存在),回退到自由函数,反之亦然
- ADL找不到模板化的自由函数
- 基于方法或自由函数存在的模板构造函数解析
- G 未定义的引用自由函数
- 为什么未调用自由函数作为构造函数中的参数传递
- 自由函数和继承
- 调用自由函数而不是方法(如果不存在)
- 如何将自由函数与对象一起使用
- 如何使用begin()自由函数