views:

290

answers:

4

I have a structure called table, I just want to create a table, like constructor in java, but when i call this function in main, it gives segmentation fault

struct table *create(char *name,int number,char *s_name)
{
  struct table *newTable;
  newTable->name = name;
  newTable->number = number;
  newTable->s_name = s_name;
  return newTable;
}
+8  A: 

You haven't allocated any memory for the object, and are de-referencing fields of the structure. You need to use malloc to allocate memory for newTable before accessing it

Larry Watanabe
+10  A: 
struct table *newTable = malloc(sizeof(struct table));

Don't forget calling free when you're done using it, as C does not have a Garbage Collector like java has.

Daniel
That should be either `sizeof (struct table)` or `sizeof *newTable` (I prefer the latter). Unlike C++, struct tags must be preceded by the `struct` keyword.
John Bode
@John: unless table is typedeffed... I edited it anyway.
Daniel
A: 

you are trying to access unallocated/uninitialized memory & SIGSEGV (Segmentation Fault) is perfectly alright for the code unless you allocate memory explicitly using malloc or other memory allocation methods.

A: 

Try:

struct table *create(char *name,int number,char *s_name)
{
  struct table *newTable = malloc(sizeof(*newTable));
  if (!newTable)
    return NULL;

  newTable->name = name;
  newTable->number = number;
  newTable->s_name = s_name;
  return newTable;
}

Another word of caution: in this code, newTable->name just points to the provided name, no copy is made. This may not be what you want, but it's hard to tell from this small snippet. An alternative is to duplicate the name. The same goes for s_name.

Eli Bendersky
use strdup() to do this for name and s_name as eliben mentioned. Assigning them is a no-no.
tommieb75