номер столбца 1 находится вне диапазона 0 ..- 1 - PullRequest
0 голосов
/ 24 апреля 2018

Я написал функцию, в которой хочу передать указатель на массив структур. Я делаю new() внутри него и хочу заполнить его данными, полученными из структуры PGresult (res). Однако я получил ошибки:

column number 0 is out of range 0..-1 
column number 1 is out of range 0..-1 
column number 2 is out of range 0..-1 
column number 3 is out of range 0..-1
Segmentation fault (core dumped)

вот моя функция

Database::selectAnnouncements(const int user_id, const char *cat_id, struct announcementStruct **pStruct, int *size) {

*size = PQntuples(res);

struct announcementStruct * ann = new struct announcementStruct[PQntuples(res)];
*pStruct =  ann;
int cr_fnum = PQfnumber(res, "created_on");
int con_fnum = PQfnumber(res, "content");
int cat_fnum = PQfnumber(res, "category");
int rm_fnum = PQfnumber(res, "remove_on");


for (int i = 0; i < PQntuples(res); i++) {
        const char *cr_val = PQgetvalue(res, i, cr_fnum);
        const char *con_val = PQgetvalue(res, i, con_fnum);
        const char *cat_val = PQgetvalue(res, i, cat_fnum);
        const char *rm_val = PQgetvalue(res, i, rm_fnum);
        (*pStruct[i]).creation_date = new char[strlen(cr_val)];
        (*pStruct[i]).content = new char[strlen(con_val)];
        (*pStruct[i]).category = new char[strlen(cat_val)];
        (*pStruct[i]).removal_date = new char[strlen(rm_val)];
        strcpy((*pStruct[i]).creation_date, cr_val);
        strcpy((*pStruct[i]).content, con_val);
        strcpy((*pStruct[i]).category, cat_val);
        strcpy((*pStruct[i]).removal_date, rm_val);
}

for (int i = 0; i < PQntuples(res); i++) {
        printf("%s  ", (pStruct[i]->creation_date));
        printf("  %s  ", (pStruct[i]->content));
        printf("  %s  ", (pStruct[i]->category));
        printf("  %s  ", (pStruct[i]->removal_date));
        printf("\n");
}
PQclear(res);

}

вот как я это использую

struct announcementStruct *announcements = NULL;
int size;
db.selectAnnouncements(0, "DOGS", &announcements, &size);

1 Ответ

0 голосов
/ 25 апреля 2018

Вы определенно забыли обнулить строки. Выделите strlen + 1, чтобы соответствовать нулю. Забыть нулевое значение - это легкая причина появления ошибок. Такие функции, как strncpy snprintf, помогают обеспечить безопасность.

Комментарий Кевина также правильный. Убедитесь, что вы получили все 12 экземпляров этой ошибки (исходные 4, четыре в strcpy и 4 в printf)

...