2011-12-25 171 views
1

几个星期前,我是用了第一次(我不习惯使用它们)漂浮双打,我有比较操作数的一些问题。我在尝试为这种类型赋值时也遇到了问题,但我也解决了这个问题...“unsigned long int类型”和“无符号长long int型的收入分配问题

今天,我在C++中创建了一个库,并且发现了一个错误... ......奇怪?或者只是我愚蠢的想法?

这是代码:

ini::ini(const char * path, bool _autoflush_ /*= false*/) { 
/* Storing file name ... */ 
f_name = new char[strlen(path)+1]; 
strcpy(f_name, path); 

/* Storing autoflush ... */ 
autoflush = _autoflush_; 

/* First step: getting file size */ 
    /* Open the file in read/append mode */ 
    FILE * fd = fopen(path, "r"); 
    /* On non-valid descriptor, goto next step directly */ 
    if(fd == NULL) f_size = 1; goto allocbuffer; 

    /* Seek to the end */ 
    fseek(fd, 0, SEEK_END); 
    /* Get file size */ 
    f_size = (unsigned long int)ftell(fd) + 1; 

/* Second step: allocating memory for the buffer */ allocbuffer: 
    cout << endl << endl << endl << endl << "Wanting " << sizeof(char)*f_size << " bytes of memory!" << endl << endl << endl << endl; 
    /* Allocate buffer-space */ 
    buffer = (char*)malloc(sizeof(char)*f_size); 
    if(buffer == NULL) { 
     errord = (char*)malloc(strlen(INI_ERROR_NOT_ENOUGH_MEMORY) + 1); 
     strcpy(errord, INI_ERROR_NOT_ENOUGH_MEMORY); 
     cout << endl << endl << endl << endl << "Last error: \"" << errord << "\"." << endl << endl << endl << endl; 
     return; 
    } 
    /* Initialize and fill it with null bytes */ 
    memset(buffer, 0, f_size); 
    /* Goto next step */ 
    if(fd == NULL) goto endconstruct; 

/* Third step: storing in the buffer */ loadbuffer: 
    /* Rewind file descriptor */ 
    rewind(fd); 
    /* Read from file */ 
    if(fread(buffer, 1, f_size, fd) != f_size) { 
     errord = (char*)malloc(strlen(INI_ERROR_NOT_READED) + 1); 
     strcpy(errord, INI_ERROR_NOT_READED); 
     cout << endl << endl << endl << endl << "Last error: \"" << errord << "\"." << endl << endl << endl << endl; 
     cout << endl << endl << endl << endl << "BYTES OF FILE: \"" << f_size << "\"." << endl << endl << endl << endl; 
    } 
    /* Close file descriptor */ 
    fclose(fd); 
    /* Get number of lines */ 
    f_line = strnum(buffer, "\n") + 1; 

/* End building of object */ 
endconstruct: 
    /* Print out what is stored in the buffer NOW */ 
    cout << endl << endl << endl << endl << "Buffer is:" << endl << buffer << endl << endl << endl << endl; 

return; 

}

大概INI库已经建立,且远优于我。但是我从C开始学习C++,并且想要练习一些有趣而有用的东西。我错过了类声明,我不知道是否有必要将其粘贴在这里,但这里是:

/** @def INI_ERROR_NOT_READED 
    @brief <em>Not readed as many bytes as required</em> 
*/ 
#define INI_ERROR_NOT_READED "Not readed as many bytes as required" 
/** @def INI_ERROR_NOT_ENOUGH_MEMORY 
    @brief <em>There is not enough memory</em> 
*/ 
#define INI_ERROR_NOT_ENOUGH_MEMORY "There is not enough memory" 

/** @class ini 
    @brief Class to describe <em>ini</em> files. 

    It describes an ini file. All the file is readed and loaded 
    in memory, for faster access. This class is the 
    improved & C++ version of the old, monstruous 
    functions defined in the old, monstruous IO Utilities 
    Library. Writting functions use dynamic memory reallocation 
    and file flush to the filesystem. 
*/ 
class ini { 
    public: 
     /** @brief Constructor. Gives initial memory for the buffer and loads all the file in that buffer. 
     * 
     * @param path - Path of the <em>ini</em> file to open. 
     * @param _autoflush_ - Whether to auto-flush changes to hard disk or not. 
     * If you don't set it to any value, <em>false</em> is taked as default 
     * value and you have to flush changes manually using member function flush(). 
     * Setting it to <em>true</em> may make it less efficient, so be careful 
     * if you're going to make a lot of changes in the <em>ini</em> file. 
     */ 
     ini      (const char * path, bool _autoflush_ = false); 
     /** @brief Destructor. Frees the memory pointed by <em>buffer</em> and destroys the #ini object. 
     * 
     * It's very important to free the memory buffer, to avoid memory corruptions. 
     */ 
     ~ini     (void); 
     /** @brief Gets last error stored in private member <em>errord</em>. 
     * 
     * @return Last error-descriptor as string. 
     */ 
     char *  geterror (void); 
     /** @brief Flush changes made in the buffer to the hard disk. 
     * 
     * You can do it manually or set auto-flushing by the second argument of 
     * ini::ini(). 
     * 
     * @par Example of usage: 
     * @code 
     * ini inid("myini.ini"); 
     * // make changes 
     * inid.flush(); 
     * @endcode 
     */ 
     void  flush  (void); 
     /** @brief Flush changes made in the buffer to *another* file the hard disk. 
     * 
     * Using this function instead of normal flush(void), you are able to 
     * save the buffer to another #ini file that is not the original one. 
     * 
     * @par Example of usage: 
     * @code 
     * ini inid("myini.ini"); 
      * // make changes 
     * inid.flush("myini.backup.ini"); 
     * @endcode 
     */ 
     void  flush  (const char * path); 
     /** @brief Checks if a section exists. 
     * 
     * @param tsection - The name of the section to check, without the braces. 
     * 
     * @return #true if the section exists; #false if not. 
     */ 
     bool  sectExists (const char * tsection); 
     /** @brief Gets the line in that a section starts. 
     * 
     * @param tsection - The name of the section to check, without the braces. 
     * 
     * @return The line in that the section starts; -1 if not-founded section. 
     * Keep in mind that the first line is 1, the second, 2,... 
     */ 
     int   sectStart (const char * tsection); 
     /** @brief Gets the line in that a section ends. 
     * 
     * @param tsection - The name of the section to check, without the braces. 
     * 
     * @return The line in that the section ends; -1 if not-founded section. 
     * Keep in mind that the first line is 1, the second, 2,... 
     */ 
     int   sectStop (const char * tsection); 
     /** @brief Checks if a key exists. 
     * 
     * @param tsection - The name of the section to check, without the braces. 
     * If the key is outside any section (if it's a #KWOS), then <em>tsection</em> 
     * should be #KWOS. 
     * @param tkey - The name of the key to check. 
     * 
     * @return #true if the key exists in the specified section; #false if not. 
     */ 
     int   keyExists (const char * tsection, const char * tkey); 
     /** @brief Reads the value of a key as a string. 
     * 
     * @param tsection - The name of the section to read from, without the braces. 
     * If the key is outside any section (if it's a #KWOS), then <em>tsection</em> 
     * should be #KWOS. 
     * @param tkey - The name of the key to read its value. 
     * @param tval - The default string to return if cannot found the key. 
     * 
     * @return The value of the key <em>tkey</em> in section <em>tsection</em>; or 
     * <em>tval</em> when non-existing key. 
     */ 
     char *  read  (const char * tsection, const char * tkey, const char * tval); 
     /** @brief Reads the value of a key as an integer value. 
     * 
     * @param tsection - The name of the section to read from, without the braces. 
     * If the key is outside any section (if it's a #KWOS), then <em>tsection</em> 
     * should be #KWOS. 
     * @param tkey - The name of the key to read its value. 
     * @param tval - The default value to return if cannot found the key. 
     * 
     * @return The value of the key <em>tkey</em> in section <em>tsection</em>; or 
     * <em>tval</em> when non-existing key. 
     */ 
     long int readi  (const char * tsection, const char * tkey, int tval); 
     bool  delKey  (const char * tsection, const char * tkey); 
     bool  delSect  (const char * tsection); 
     bool  write  (const char * tsection, const char * tkey, const char * tval); 
     bool  write  (const char * tsection, const char * tkey, int tval); 
    private: 
     unsigned long int  f_size; /**< File size. */ 
     unsigned int   f_line; /**< Number of lines of the <em>ini</em> file. */ 
     char *     buffer; /**< Memory buffer to store data. Dynamimcally reallocated. */ 
     char *     f_name; /**< File name. */ 
     bool     autoflush; /**< Whether to auto-flush to hard disk or not. */ 
     char *     errord; /**< Last error stored internally by the functions of the #ini class. */ 
}; 

几个“测试”之后,我终于发现,问题出在“f_size”变量。为什么?不知道。但是,如果我将它打印到标准输出,它显示一个非常非常大的数字。这是内存分配(带malloc)错误以及从文件读取(或使用memset初始化)后续错误的问题。

非常感谢帮助。并链接,参考或解释让我看到我的错误,并继续学习。

谢谢!

P.S .:我在Linux Debian“squeeze”中使用g ++,amd64。

+2

顺便说一句'strlen'和'new char []'?即使'malloc'?你仍然在思考C语言,使用'std :: string'并繁荣 – Kos 2011-12-25 17:39:21

+0

但是我见过的很多函数'仍然'使用_const char * _和_char * _...,我需要_realloc_来动态地重新分配内存缓冲区。 – 2011-12-25 17:40:50

+1

如果你不写一个容器类,为什么你需要一个动态的重新分配内存缓冲区? – Kos 2011-12-25 17:42:55

回答

3

这是一个微妙的,但显著的问题:

if(fd == NULL) f_size = 1; goto allocbuffer; 

如果文件确实存在,逻辑仍然跳转到标号allocbuffer

要解决此问题,请使用大括号。并缩进水晶清晰度。

if(fd == NULL) 
{ 
     f_size = 1; 
     goto allocbuffer; 
} 

通过跳到出口,变量没有正确初始化。

2

除了wallyk指出的问题,当ftell遇到错误时,它返回-1并将其转换为无符号long会导致溢出。在任何情况下,don't use ftell to get a file's size。使用fstat或类似的。

0

我不会调试你的代码(这更多属于codereview.se),但这里有一些提示:

f_name = new char[strlen(path)+1]; 
strcpy(f_name, path); 

相反:定义f_name为std::string,做...

f_name = path; 

 errord = (char*)malloc(strlen(INI_ERROR_NOT_READED) + 1); 
     strcpy(errord, INI_ERROR_NOT_READED); 
     cout << "Last error: \"" << errord << "\"." << endl; 

你一样,动态分配内存只写一个字符串到屏幕? 而是做简单:

 errord = INI_ERROR_NOT_READED; 
     cout << "Last error: \"" << errord << "\"." << endl; 

而且读取整个文件到缓冲区中,有更简单的方法(如,的几行代码)。见https://stackoverflow.com/a/2602060/399317


长话短说:new[]malloc是不是你的朋友,除非你正在写自己的容器。改用STL容器(例如std::vectorstd::string也有帮助)。

+0

谢谢!因此,我将使用std :: string和... @Kos ...'直接'分配'errord'?但是,那么我会得到一个seg故障或类似的东西。指针是我过去许多问题的来源......'错误'是班'ini'的私人成员。 'cout'在这种情况下只是为了在seg故障之前打印出来...... – 2011-12-25 17:55:07