0

i have to do with my friend a program in C for my school. The problem is, when i would malloc a pointer, it doesn't work, and the application will crashed. But not in debug mod. In debug mod, it works. This is a part of my code:

#include <bplus.h>

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LOG "log.txt"
#define LOGIDX "log.idx"

struct event {
    time_t nb;
    char *username;
    int type;
    char *message;
};

struct eventlist {
    struct event event;
    struct eventlist *nextelem;
};

struct eventlist *getEventList(time_t date);
void insert(struct eventlist *list, struct eventlist *event);
struct event getEventFromString(char *str);
char *getLine(FILE *file);
int file_exists(const char *fname);
char *dechiffrer(const char *pChaineChiffree);

int main(void) {
    time_t timenow = time(NULL);
    struct tm *tm = gmtime(&timenow);
    tm->tm_hour = 0;
    tm->tm_min = 0;
    tm->tm_sec = 0;
    time_t time = mktime(tm);
    struct eventlist *list = getEventList(time);
    return 0;
}

struct eventlist *getEventList(time_t date) {
    int end = 0;
    FILE *file = NULL;
    char str[20];
    char *line = NULL;
    char *uncode = NULL;
    ENTRY e;
    IX_DESC faddress;
    struct eventlist *list = NULL;  //  Liste a retourner
    struct event *event = NULL; //  Contient l'evenement
    struct eventlist *templist = NULL;  //  Contient l'evenement a mettre dans list
    //  On ouvre / crée le fichier .idx
    if (file_exists(LOGIDX))
        open_index(LOGIDX, &faddress, 0);
    else
        make_index(LOGIDX, &faddress, 0);

    //  On ouvre le fichier de log
    if ((file = fopen(LOG, "rb")) != NULL) {
        //  On met dans e.key le temps
        sprintf(str, "%d", (int) date);
        strcpy(e.key, str);
        if (find_key(&e, &faddress)) {  //  Si la clé existe
            fseek(file, e.recptr, SEEK_SET);    //  On se positionne
            line = getLine(file);   //  On récupère la ligne
            while (!feof(file) && !end) {   //  Boucle principale
                printf("\ngetEventList 1");
                if (line != NULL) {
                    uncode = dechiffrer(line);  //  On déchiffre la ligne
                    printf("\ngetEventList 2");
                    event = (struct event *) malloc(sizeof(struct event *) * 1);    //  On alloue de la place
                    printf("\ngetEventList 3");
                    if (event) {
                        *event = getEventFromString(uncode); //  On la transforme en structure
                        printf("\ngetEventList 4");
                        if (event->nb < date + 86400) {
                            templist = (struct eventlist *) malloc(sizeof(struct eventlist *) * 1);
                            printf("\ngetEventList 5");
                            if (templist) {
                                templist->event = *event;
                                templist->nextelem = NULL;
                                printf("\ngetEventList 6");
                                if (list == NULL)
                                    list = templist;
                                else
                                    insert(list, templist);
                                printf("\ngetEventList 7");
                                line = getLine(file);   //  On récupère la ligne
                                printf("\ngetEventList 8");
                            } else {
                                list = NULL;
                                end = 1;
                            }
                        } else
                            end = 1;
                    } else {
                        list = NULL;
                        end = 1;
                    }
                } else
                    end = 1;
            }
        } else {    //  Sinon, on affiche un message
            list = NULL;
            printf("\nErreur: Clé non trouvée !");
        }
        fclose(file);
    } else {
        list = NULL;
        printf("\nErreur lors de l'ouverture du fichier !");
    }
    return list;
}

void insert(struct eventlist *list, struct eventlist *event) {
    struct eventlist *temp = list;
    struct eventlist *lasttemp = NULL;
    printf("\n(%s %s)", temp->event.username, event->event.username);
    while (temp->nextelem != NULL && stricmp(temp->event.username, event->event.username)) {
        temp = temp->nextelem;
    }
    lasttemp = temp;
    while (temp != NULL && !stricmp(temp->event.username, event->event.username)) {
        lasttemp = temp;
        temp = temp->nextelem;
    }
    event->nextelem = temp;
    lasttemp->nextelem = event;
}

struct event getEventFromString(char *str) {
    struct event event;
    event.nb = 0;
    event.type = 0;
    event.username = NULL;
    event.message = NULL;
    int time;
    int type;
    char *username = (char *) malloc(sizeof(char *) * strlen(str));
    char *message = (char *) malloc(sizeof(char *) * strlen(str));
    if (sscanf(str, "%d %d %s %[^\n]s", &(time), &(type), username, message)) {
        event.nb = (time_t) time;
        event.type = type;
        event.username = username;
        event.message = message;
    }
    return event;
}

char *getLine(FILE *file) {
    char *line = NULL;
    unsigned char c;
    int end = 0;
    int ln = 0;
    printf("\ngetLine 1");
    line = (char *) malloc(sizeof(char *) * 1);
    printf("\ngetLine 2");
    if (line != NULL) {
        while(!feof(file) && !end) {
            c = fgetc(file);
            if (c != '\n' && c != '\r') {
                printf("\nDEBUG: %c %d %s", c, ln, line);
                line = (char *) realloc(line, sizeof(char *) * (ln + 2));
                if (line != NULL) {
                    line[ln++] = c;
                    line[ln] = '\0';
                } else
                    end = 1;
            } else
                end = 1;
        }
        line[ln] = '\0';
    }
    if (line[0] == '\0' || line[1] == '\0')
        line = NULL;
    return line;
}

int file_exists(const char *fname) {
    FILE *file;
    int returncode = 0;
    if ((file = fopen(fname, "r"))) {
        fclose(file);
        returncode = 1;
    }
    return returncode;
}

char *dechiffrer(const char *pChaineChiffree) {
    char *dechiff;
    unsigned char car;
    unsigned int i;
    dechiff = malloc(strlen(pChaineChiffree) + 1);

    for (i = 0; pChaineChiffree[i] != '\0'; i++) {
        car = pChaineChiffree[i];
        car = (car & 0x0F) << 4 | (car & 0xF0) >> 4;
//        car -= 0x55;
        dechiff[i] = car;
    }
    dechiff[i] = '\0';
    return dechiff;
}

I think it's a bufferoverflow, but i don't know where is the problem, and why it's bugged. The crash occured in this malloc:

printf("\ngetLine 1");
line = (char *) malloc(sizeof(char *) * 1);
printf("\ngetLine 2");

Please help me

Thanks

0ddlyoko

EDIT:

Ok i've found the problem, it was with all my sizeof(XXX *), i've just changed this to sizeof(XXX). Thanks !

0ddlyoko
  • 310
  • 4
  • 14
  • `line = (char *) realloc(line, sizeof(char *) * (ln + 2));` ==> `line = realloc(line, ln + 2);` – mch May 13 '17 at 20:42
  • 1
    @mcn (and to author), `x = realloc(x, ...);` is a **bad** idea. – 0andriy May 13 '17 at 20:43
  • Thanks mch ! This with all my sizeof(XXX *), i just have to edit this to sizeof(XXX), and why is it a bad idea to realloc ? – 0ddlyoko May 13 '17 at 20:48
  • @0ddlyoko you need to check if `realloc` returned `NULL`, because that means that more memory could not be allocated. You could end up leaking the data you _do_ have... – Charles May 13 '17 at 20:51
  • Yes i know, but in my code i'm checking if `realloc` and `malloc` return `NULL` or not ? – 0ddlyoko May 13 '17 at 20:58
  • For future reference, the best available tool for tracking down this kind of bug is [`valgrind`](http://valgrind.org). Fix the _very first_ problem it tells you about, repeat until working. – zwol May 13 '17 at 21:04
  • `line = (char *) realloc(line, sizeof(char *) * (ln + 2)); if (line != NULL) {}`-- you check to see if `realloc()` returned a null pointer, but then it is too late, and you have lost the pointer to the previously allocated memory. This should be stored in a temporary variable and checked before assigning to `line`. Also, you should read about [why using `feof()` to control a file loop is a bad idea](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong). – ad absurdum May 14 '17 at 01:16

0 Answers0