Frage

I have a structure as below

typedef struct

 {
   char table_version_major[2];
   char table_version_minor[2];
 } SOFT_VER_DATA;

 #define Soft_Ver_Total_Datasets 1;

I use the following function

void prepare_Soft_Ver_File_for_Upload(void)
  {
    Glib::ustring l_temp;
    int l_data_sets=0;
    char l_query_string [100];
    SOFT_VER_DATA l_soft_ver_data[Soft_Ver_Total_Datasets];
    SACommand* l_db_cmd=get_database_command_object();
    string l_profile = g_profile_label->get_text();
    sprintf(l_query_string,"SELECT * from SoftVer WHERE PROF = "%s",l_prof_name.data());
    set_sql_query(l_query_string);
    execute_sql_query();

    while(l_db_cmd->FetchNext())
     {
       l_temp=l_db_cmd->Field("PROF1_1").asString();                                    //PROF1_1 is an access database column, 1st entry contains abc
       strncpy(l_soft_ver_data[l_datasets].table_version_major,l_temp.data(),2);
       cout<<"\n Major Value: "<<l_soft_ver_data[l_datasets].table_version_major;


        l_temp=l_db_cmd->Field("PROF1_2").asString();
        //PROF1_2 is an access database column, 1st entry contains def
        strncpy(l_soft_ver_data[l_datasets].table_version_minor,l_temp.data(),2);
        cout<<"\n Minor Value: "<<l_soft_ver_data[l_datasets].table_version_minor;

        l_data_sets++;
        }

When i run the program i expect Major Value to be "ab" whereas minor value to be "de". The program output is as below.

Major Value: ab Minor Value: deSELECT * from SoftVer WHERE PROF = 'new_prof'

I tried to zero the rest of the byte by using the following

        l_soft_ver_data[l_datasets].table_version_major=0;
        l_soft_Ver_data[l_datasets].table_version_minor=0;

Now i get the correct ouput but when i read these values with gktmm text fields, i get

abde(and some shaded square)

and

gh(and some shaded square)

here is my gtkmm part

    m_row[m_soft_model.table_version_major] = m_soft_ver_data[l_i].table_version_major;

    m_row[m_soft_model.table_version_minor] = m_soft_ver_data[l_i].table_version_minor;


    Both are Glib::ustring
War es hilfreich?

Lösung

strncpy() does not ensure that the resulting string is null-terminated. If you're expecting "ab" to be stored in the table_version_major[] field, you'll need that array to be at least 3 bytes in size to allow for the terminating '\0', and you'll need to explicitly set table_version_major[2] = '\0' since strncpy() will not do that for you.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top