I'm not understanding something simple.

I have this sample code:

typedef struct {
  char* fname;
} PersonType;

int main() {
  PersonType *p;
  p  = (PersonType *)malloc(sizeof(PersonType));
  char * name = "Robert";

  /* this next line causes a segmentation fault */  
  strcpy(p->fname, name);

  printf("name: %s\n", p->fname);

}

Why is there a segmentation fault at the 'strcpy'? What am I doing wrong?

Any help is greatly appreciate, thanks!

Rob

有帮助吗?

解决方案 2

Your PersonType struct contains a pointer to a string that you are never allocating, nor assigning. So fname is an uninitialized pointer that you are attempting to write to. You need to allocate a buffer for fname.

int main() {
   PersonType *p;
   p  = (PersonType *)malloc(sizeof(PersonType));
   p->fname = malloc(sizeof(char)*7);
   char * name = "Robert";

Either that or make fname a char array so that your struct will contain a buffer within itself.

其他提示

Although you allocated space for the structure, you've neither allocated space for the string nor initialized the pointer in the structure. You need to use something like:

if (p != 0)
{
    if ((p->fname = malloc(strlen(name) + 1)) != 0)
        strcpy(p->fname, name);
    else
        free(p);  // Report error too?
}

Note that this checks the results of the memory allocation. I'm not fussed about whether you cast the return type for malloc(); other people are.

fname is not initialized to anything. strcpy will continue to read starting at the location fname points to until it encounters \0.

Either make fname an array, and initialize it. Or allocate fname and initialize it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top