Question

I'm having problems with delete on c++. I'm not sure if I understand when I leak memory and when I don't. But according to Visual Studio there are leaks.

Is this leaking memory? The actual method is bigger and I want to use c as part of an struct.

char *c=copio("hola");
char *copio(char * c1)
{
    char * ret=new char[strlen(c1)+1];
    strcpy(ret,c1);
    return ret;
};

And this? In this case aux is auxiliar, so I don't use it when I leave the big method

archivo *aux=ultimoArchivo(m->listaArchivos);
archivo * ultimoArchivo(archivo* lista){
    if(lista==NULL){
        return NULL;
    }else{
        if(lista->sig==NULL){
            return lista;
        }else{
            return ultimoArchivo(lista->sig);
        }
    }
}

Thanks

Était-ce utile?

La solution

In the first code snippet, you have to make sure that after you're done using the pointer returned by copio you delete it, otherwise you end up with a memory leak. But as the others said, unless this is an exercise, use std::string for string manipulation, or, if not, at least declare your own class and do the delete in the destructor (or use a std::unique_ptr or std::shared_ptr, i.e. a smart pointer).

I don't understand your second code snippet, it looks like there are no allocations there so don't know how you can end up with a memory leak.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top