如何释放 C++/C 格式的内存?我什么时候会写自由(a);?函数是重新指针

How can i free memory in C++/C? When would i write free(a);? Function is returing pointer

本文关键字:自由 函数 指针 新指针 什么时候 C++ 何释放 释放 格式 内存      更新时间:2023-10-16

代码:

#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 * 来完全避免此问题。