문제

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