R
Ramprasad A Padmanabhan
I have got a pretty simple script , that uses bsearch to look for a
particular element
The problem is , it simply segfaults inside the compare function.
I have a similar script that works fine , and now this simply segfaults.
I am driving myself nuts , last 4 hrs , why such a simple thing would
not work
Pls someone help
Thanks
Ram
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct aliasid {
char a_id[100];
int count;
};
int compare_aliases(const void *p1, const void *p2 ){
const struct aliasid *u1 = (const struct aliasid *) p1;
const struct aliasid **u2 = (const struct aliasid **) p2;
return(strcmp(u1->a_id,(*u2)->a_id));
}
struct aliasid* new_aliasid(char* id,int numids) {
struct aliasid* a;
a = malloc(sizeof(struct aliasid) +10);
strcpy(a->a_id,id);
a->count = 0;
return(a);
}
int main(int argc,char* argv[]){
struct aliasid **aliases , **tmp1;
char the_string[100];
aliases = malloc(3 * sizeof(void*));
if(aliases == NULL ) {
printf("malloc failed");
exit(1);
}
aliases[0]= new_aliasid("abc",3);
aliases[1]= new_aliasid("def",3);
aliases[2]=NULL;
tmp1 = (struct aliasid **) bsearch("abc",aliases,2,sizeof( struct
aliasid),compare_aliases);
if(tmp1 == NULL){
printf("The id %s was not found\n",the_string);
} else {
printf("The id %s was found\n",the_string);
}
return(0);
}
particular element
The problem is , it simply segfaults inside the compare function.
I have a similar script that works fine , and now this simply segfaults.
I am driving myself nuts , last 4 hrs , why such a simple thing would
not work
Pls someone help
Thanks
Ram
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct aliasid {
char a_id[100];
int count;
};
int compare_aliases(const void *p1, const void *p2 ){
const struct aliasid *u1 = (const struct aliasid *) p1;
const struct aliasid **u2 = (const struct aliasid **) p2;
return(strcmp(u1->a_id,(*u2)->a_id));
}
struct aliasid* new_aliasid(char* id,int numids) {
struct aliasid* a;
a = malloc(sizeof(struct aliasid) +10);
strcpy(a->a_id,id);
a->count = 0;
return(a);
}
int main(int argc,char* argv[]){
struct aliasid **aliases , **tmp1;
char the_string[100];
aliases = malloc(3 * sizeof(void*));
if(aliases == NULL ) {
printf("malloc failed");
exit(1);
}
aliases[0]= new_aliasid("abc",3);
aliases[1]= new_aliasid("def",3);
aliases[2]=NULL;
tmp1 = (struct aliasid **) bsearch("abc",aliases,2,sizeof( struct
aliasid),compare_aliases);
if(tmp1 == NULL){
printf("The id %s was not found\n",the_string);
} else {
printf("The id %s was found\n",the_string);
}
return(0);
}