PGOnTheGo
PGOnTheGo

Reputation: 805

recurring segmentation fault while using strcpy

Getting a segmentation fault for the following code. Please advise.

struct columns {
      char* c_name;
      char* c_type;
      char* c_size;
};

int main(int argc, char* argv[])
{
  int column_num = 3;
  struct columns col[10];
  //columns *col = (columns*) malloc (sizeof(columns) * column_num);
  strcpy(col[0].c_name, "PSID");
  strcpy(col[0].c_type, "INT");
  strcpy(col[0].c_size, "4");
}

I am using 2 ways to allocate space for columns structure but continue to get a segmentation fault. Am I missing something?

Upvotes: 0

Views: 181

Answers (5)

mrk
mrk

Reputation: 3191

Try this (strdup takes care of storage but remember to free when you are done):

struct columns {
  char* c_name;
  char* c_type;
  char* c_size;
};

int main(int argc, char* argv[])
{
  int column_num = 3;
  struct columns col[10];

  col[0].c_name = strdup("PSID");
  col[0].c_type = strdup("INT");
  col[0].c_size = strdup("4");

  return 0;
}

Upvotes: 2

orlp
orlp

Reputation: 117681

col[0].c_name is a pointer, but doesn't point to any memory. That's why it will segfault.

Before copying anything in it allocate some memory using an array char c_name[256]; or malloc().

Upvotes: 2

user405725
user405725

Reputation:

You allocate space for columns structure, but not for strings that you want to store. Your pointers (i.e. c_name) are left uninitialized, pointing to some random memory locations, thus you invoke undefined behavior right away.

Upvotes: 1

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143081

You never allocate memory and initialize your char* pointers.

Like

strcpy(col[0].c_name=malloc(sizeof "PSID"),"PSID");

Of course, you need to check for errors and make it otherwise meaningful.

Upvotes: 1

Ry-
Ry-

Reputation: 224904

None of your pointers in the structure are actually initialized to anything. You have to give them a dimension, or dynamically allocate some memory for them.

Upvotes: 5

Related Questions