Re: ...malloc ...from Rome...and Big Chris

From: lasek (claudio.rossetti_at_acrm.it)
Date: 10/19/04


Date: Tue, 19 Oct 2004 04:30:38 -0400

Hiiiiii....always from Rome....and today the weather is a little
dirt...(like Alice in Chains....);however, i've a little script that
allocate memory for first time when i created the 'agenda':

naturally start is global an it was declared:

struct agenda
{
  char acNome[20];
  struct agenda *next;
};

typedef struct agenda lista_agenda;

lista_agenda *start=NULL;

void crea_agenda()
{
  start=(lista_agenda *)malloc(sizeof(lista_agenda));

  if(start!=NULL)
  {
    memset((char *)start->acNome,'\0',sizeof(start->acNome));

    scanf("%s",start->acNome);

    start->next=NULL;
  }
}

When i insert a new value, i need to add a new node, so:

void inserisci()
{
  char newNome[20]={0};
  unsigned int iLen;

  lista_agenda *newrecord;
  lista_agenda *locate;
  lista_agenda *localizza(lista_agenda *ptStruct);

  printf("\nNew name:");

  scanf("%s",newName);

  iLen=sizeof(newName);

  /*
  ** this function return a pointer to the last node in
  ** the list.
  */

  locate=localizza(start);

  if(newNome)
  {
    /*
    ** Now i know that cast the return value from malloc
    ** is not correct but this is my original code.
    */

    newrecord=(lista_agenda *)malloc(sizeof(lista_agenda));

    if(newrecord)
    {
      strncpy(newrecord->acNome,newNome,iLen);

      locate->next=newrecord;

      newrecord->next=NULL;
    }
    else
      printf("Impossibile allocare lo spazio richiesto.\n");
  }
}

The error i receive when i try to add a new node it depends from the
malloc function i use, in particular:

newrecord=(lista_agenda *)malloc(sizeof(lista_agenda));
This line above is ok(from my gdb).
Also because, (i think) i must allocate for the entire size of my struct
and not the size of a pointer to the struct.
(i'm not sure but if i execute a sizeof of a pointer a can see always 4
byte;maybe u'm wrong).

The line below give me an strange error from (gdb):
newrecord=(lista_agenda *)malloc(sizeof(lista_agenda*));

"
Program received signal SIGSEGV, Segmentation fault.
0x4207aecc in chunk_free () from /lib/i686/libc.so.6
(gdb) where
#0 0x4207aecc in chunk_free () from /lib/i686/libc.so.6
#1 0x4207a60a in chunk_alloc () from /lib/i686/libc.so.6
#2 0x4207a058 in malloc () from /lib/i686/libc.so.6
#3 0x08048790 in ?? ()
#4 0x08048599 in ?? ()
#5 0x42017499 in __libc_start_main () from /lib/i686/libc.so.6
".

Thanks all for your patience...