Click to See Complete Forum and Search --> : Gnu C


RomanB
February 21st, 2008, 04:46 AM
Hi guys!
Help me please.

//********************CODE*********************
int i_ini_file;

char ch_read_data_[1];
char ch_read_data[255];
int i_read_count;


typedef struct{
char ch_string[255];
int i_type;
char ch_sec_name[20];
char ch_name[20];
char ch_value[255];
} str_ini_data;

str_ini_data s_ini_data;

main(){
char ch_ini_file[255];
strcpy(ch_ini_file,"ini.ini");
int i_num = 0;

i_read_count = 0;
strcpy(ch_read_data,"");
strcpy(ch_read_data_,"");

if ((i_ini_file = open(ch_ini_file, O_RDONLY)) < 0 ){
strcpy(ch_main_error,"IniParser:iReadIniFile: Can't open file.");
return -1;
}

str_ini_data *ptr_ini_data;
ptr_ini_data = &s_ini_data;

ptr_ini_data = (str_ini_data *) malloc(sizeof(str_ini_data));

while(i_read_count = read(i_ini_file,ch_read_data_,1)){
if (ch_read_data_[0] == '\n'){
ptr_ini_data = (str_ini_data *) reallocf(ptr_ini_data,(sizeof(str_ini_data)));
stpcpy(ptr_ini_data[i_num].ch_string, ch_read_data);
printf(""); /****this string****/
strcpy(ch_read_data,"");
strcpy(ch_read_data_,"");
}
strncat(ch_read_data,ch_read_data_,1);
}

free (ptr_ini_data);
return 0;

}
//******************END CODE*******************

Code above working successfully. But if I make comment string printf(""); , a program fail down with generating core-file. WHY??? I don't understand.

Thenks you.

S_M_A
February 21st, 2008, 05:13 PM
Edit your post to use code tags please. Here's how to do it http://www.codeguru.com/forum/misc.php?do=bbcode#code

It's hard to read the code in this form but I there are no checks that protect you from buffer overflow (>255) so I guess that it has something to with that. Why is line ptr_ini_data = (str_ini_data *) reallocf(ptr_ini_data,(sizeof(str_ini_data)));needed? Re-allocation is made with same size as original malloc a few lines up (which makes the static allocation of s_ini_data unnecessary).

Have you tried running the code in a debugger (gdb for instance)?