C ++ program hangs when I use a function to get the name of a file

0

I'm doing a small IDE in c ++ and I'm having trouble getting the name of a file. ex: the full path of the file is "keywords // cplusplus.txt" however the file name is "cplusplus.txt". So I wrote a function to get the 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]='
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]='%pre%';
    return real_name;
}
'; return real_name; }

The GetName (int) function takes the full path of the file. I do not know what's wrong, because when I finished the function was working, however, after a while it started to crash and now sometimes crashes and some not. Does anyone know what's wrong? The pointers maybe?

    
asked by anonymous 08.01.2018 / 23:16

1 answer

1

The problem is in this line of code:

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

The memcpy function is copying over bytes, that is, the function is writing out of memory allocated by malloc . The right thing would be like this:

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

Now, the amount of bytes being copied is the same as the number of bytes that were allocated in malloc .

    
09.01.2018 / 10:49