0

I have a struct:

typedef struct entry_t {
  char * name;
  int lines [MAX];
  int n;/*n lines*/
} entry_t;

and a array of structs entry_t * list[MAX];

I try to use bsearch to get an entry if one exists in my following function:

int addToList(entry_t * list[], int n, const char * name, int lineNr){
  int i = 0;
  int j = 0;
  entry_t * entry;
  entry_t * sentry;
  bool found = false;
  char * tmp = (char*) malloc(sizeof(char)*MAX);

  sentry = (entry_t *) bsearch(name,list,n,sizeof(entry_t *), cmpEntries2);
    if(sentry != NULL){
        printf("%s",sentry->name);
      i = sentry->n;
      sentry->lines[i] = lineNr;
      sentry->n++;
    }
   else {
    sentry = (entry_t *) malloc(sizeof(entry_t));
    strcpy(tmp,name);
    sentry->name = tmp;
    sentry->lines[0] = lineNr;
    sentry->n = 1;
    list[n] = sentry;
    n++;
  }

  return n;
}

int cmpEntries2(const void * a, const void * b){
  assert (a != NULL);
  assert (b != NULL);
  printf("DB %s %s\n",(const char*)a,(*(entry_t **)b)->name );
  return strcmp( (const char*)a, (*(entry_t **)b)->name );
}

My db log

DB argc main
DB argv main
DB printf argc
DB printf argv
DB printf argc
DB printf argv
DB printf printf
0M:

The strange thing is, that sentry isn't null, but the name is something strange(random memory location).

Thx

alk
  • 69,737
  • 10
  • 105
  • 255
user547995
  • 2,036
  • 8
  • 33
  • 62

1 Answers1

0

sentry (when used for receiving result of bsearch()) must be of type struct entry_t **.

ensc
  • 6,704
  • 14
  • 22
  • if you remove the struct(typedef struct), your answer is correct, thx a lot – user547995 Nov 23 '14 at 23:48
  • writing `struct entry_t` and simple `entry_t` should be equal in your code. But it is usually a better style to write `struct` and to avoid the `typedef` – ensc Nov 23 '14 at 23:50