GTK+ Forums

Discussion forum for GTK+ and Programming. Ask questions, troubleshoot problems, view and post example code, or express your opinions.
It is currently Sat Dec 20, 2014 1:31 am

All times are UTC




Post new topic Reply to topic  [ 3 posts ] 
Author Message
 Post subject: free char* (GTK2)
PostPosted: Tue Oct 15, 2013 11:59 am 
Offline
Familiar Face

Joined: Fri Oct 26, 2012 10:49 am
Posts: 38
Hello!
I have a basic question to local variables and the risk of memory leak:
inside a function, which variable should I free?
should I end the function with g_free(message); g_free(test); and g_free(file)?
Thanks a lot in advance for your help;
f.e.
Code:
/**
* checks if a file is present
* @param filename : name of the file to analyze
* @return TRUE: file is present FALSE: file doesn't exist
*/
gboolean ts_check_files_present(const char *filename)
{
   char message*;
             int *test;
   FILE *file;
   char fileString[1024];
   int length=0;

   strcpy(fileString,filename);
   length = strlen(fileString);
   if (fileString[length-1] == '.') // letztes Zeichen"." und "".."
      return FALSE;
   if ((file = fopen(filename, "r")))
   {
      fclose(file);
      return TRUE;
   }
// something with the variable message and with the variable test
   return FALSE;

}


Top
 Profile  
 
 Post subject: Re: free char* (GTK2)
PostPosted: Wed Oct 16, 2013 7:16 am 
Offline
Never Seen the Sunlight

Joined: Mon Apr 28, 2008 5:52 am
Posts: 799
Location: UK
Hello,

There are no memory leaks in your code and you do not need to used g_free().
- file is of type FILE * and created with fopen() and deleted with fclose()
- message and test and both unused variables

The code sample has some problems
- You have assumed that the string filename would be less than 1024 characters. Any more than this would cause a buffer over-flow and could cause a crash or security problem
- The string copy in this case is not needed

There is an API call to test for the presence of a file. This is g_file_test() see - https://developer.gnome.org/glib/stable/glib-File-Utilities.html#g-file-test

So all you need is
Code:
    return g_file_test (filename, G_FILE_TEST_IS_REGULAR);

_________________
E.


Top
 Profile  
 
 Post subject: Re: free char* (GTK2)
PostPosted: Wed Oct 16, 2013 7:44 am 
Offline
Familiar Face

Joined: Fri Oct 26, 2012 10:49 am
Posts: 38
it helps, thanks a lot!


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC


Who is online

Users browsing this forum: Google [Bot] and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  
cron
Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group