Program in c++ hangs when I use a function to pick up a file name

Asked

Viewed 41 times

1

I’m making a small IDE in c++ and I’m having trouble getting a file name.
ex: the full file path is "Keywords//cplusplus.txt" but the file name is "cplusplus.txt".
So I wrote a function to get his real name.

char* Io::GetRealName(int file)
{
    char* full_name=GetName(file);
    int last_bar=0;
    for(int i=0;i<strlen(full_name);i++)
    {
        if(full_name[i]=='/')
        {
            last_bar=i+1;
        }
    }
    char* real_name=(char*) malloc((strlen(full_name)-last_bar)*sizeof(char));
    memcpy (real_name,full_name+last_bar,strlen(full_name));
    real_name[strlen(full_name)-last_bar]='\0';
    return real_name;
}

The Getname(int) function takes the full path of the file.
I don’t know what’s wrong, because when I finished the job was working, however, after a while began to brake and now sometimes hangs and others not.
Does anyone know what’s wrong? The pointers maybe?

  • Because you don’t write everything in C++ to make it easier, maybe the error will disappear by itself.

  • I don’t know for sure sometimes I prefer to use char* instead of string for example, it depends on the situation. In this case can not change because it already has other functions that depend on the char*.

1 answer

2

The problem is in this line of code:

memcpy (real_name,full_name+last_bar,strlen(full_name));

The function memcpy is copying extra bytes, ie the function is writing out of memory allocated by malloc. It would be right:

memcpy(real_name, full_name+last_bar,(strlen(full_name)-last_bar)*sizeof(char));

Now yes, the amount of bytes being copied is the same as what was allocated in malloc.

  • Thanks for the answer user72726, I had not noticed this error. I confused the last parameter with position instead of size. void * memcpy ( void * Destination, const void * source, size_t num ); But even putting the size still gives error, and I’m sure it comes from this function Io.Getrealname(int), I’ll keep trying.

  • @gamewacko, what error is appearing? Adds a description of the error at the end of the question, and changes the code since you made changes to it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.