Ciao a tutti..Devo implementare in c un database. Io ho pensato di usare le seguenti strutture:
codice:
typedef struct campo{
char* content;
struct campo* next;
} CAMPO;
typedef struct record{
int num_campi;
CAMPO* dato;
struct record* next;
} RECORD;
Tra le funzioni che ho sviluppato c'è la seguente:
codice:
int addField(RECORD* r, char* s){
CAMPO* temp, *new = NULL;
if(r == NULL || s == NULL || strcmp(s, "") == 0)
return 1;
if((new = (CAMPO*)malloc(sizeof(CAMPO))) == NULL){
return 1;
}
if((new->content = (char*)malloc(sizeof(char)*strlen(s))) == NULL)
return 1;
strcpy(new->content, s);
if(r->dato == NULL)
r->dato = new;
else{
temp = r->dato;
while(temp->next != NULL)
temp = temp->next;
temp->next = new;
}
new->next = NULL;
return 0;
}
..ed il main che ho scritto è il seguente:
codice:
int main(void){
RECORD* rec = NULL;
CAMPO* temp = NULL;
if((rec = createRecord("uno", "due", "tre", NULL)) == NULL)
printf("errore creazione\n");
else{
temp = rec->dato;
while(temp != NULL){
printf("dato: %s,\n", temp->content);
temp = temp->next;
}
printf("campo numero 2: %s\n", getField(rec, 2));
if(setField(rec, 2, "maremmamaiala") != 0)
printf("errore setField!\n");
printf("ora il campo vale: %s\n", getField(rec, 2));
printf("numero campi per r: %i\n", getNumFields(rec));
if(addField(rec, "merdaccia") != 0)
printf("errore aggiunta campo\n");
temp = rec->dato;
while(temp != NULL){
printf("dato(dopo l'aggiunta): %s,\n", temp->content);
temp = temp->next;
}
}
deleteRecord(rec);
return 0;
}
Il compilatore dice che è tutto ok, al momento poi della addField nel main viene fuori un segmentation fault relativo alla seconda malloc(su new->content) e quello che mi dice il gdb è:
Breakpoint 1, addField (r=0x804a008, s=0x8048e30 "pisa") at help_project.c:26
26 CAMPO* temp, *new = NULL;
(gdb) n
28 if(r == NULL || s == NULL || strcmp(s, "") == 0)
(gdb) p temp
$1 = (CAMPO *) 0xb7f27ff4
(gdb) p new
$2 = (CAMPO *) 0x0
(gdb) n
30 if((new = (CAMPO*)malloc(sizeof(CAMPO))) == NULL){
(gdb)
33 if((new->content = (char*)malloc(sizeof(char)*strlen(s))) == NULL)
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0xb7e48dd8 in ?? () from /lib/tls/i686/cmov/libc.so.6
Credo che il problema sia nell'indirizzo iniziale assegnato a temp che non è 0x0 come di consueto. Spero di aver postato il codice nel modo giusto. Grazie in anticipo vi prego aiutatemi non capisco cosa c'è di sbagliato!!