I have a struct defined as
struct _element;
typedef struct _element Element;
struct _element {
char* StudentName;
char* StudentID;
int StudentMarks;
};
A pointer to an Element struct is declared globally as
Element * ePtr;
Now I have a function that returns a pointer to an Element struct. This is defined as shown below. The same ePtr which was declared globally is populated in this function and then returned.
Element * CreateElement(char * jName, char * jID, int jMarks)
{
printf("CreateElement \n");
puts(jName); puts(jID); printf("%d\n",jMarks);
ePtr->StudentName = (char*)malloc(sizeof(char)*strlen(jName));
strcpy(ePtr->StudentName, jName);
printf("After Creation \n");
puts(ePtr->StudentName);
return ePtr;
}
I am calling this function using
ePtr = CreateElement(iName,iID,iMarks);
from another function. The values stored in the parameters are correct, as shown by puts and printf commands just below the function call line.
My problem is that I’m getting a segmentation fault at the
ePtr->StudentName = (char*)malloc(sizeof(char)*strlen(jName));
line. I checked the same using gdb.
Are you allocating any memory for
ePtr?Just declaring a pointer to this struct globally isn’t enough: you’ll need to
mallocsome memory for it also:ePtr = malloc(sizeof(Element);.Also be sure to add an extra slot in the
mallocfor your strings for the null terminator.Generally, always initialize your pointers to
NULL– you can do that when you declare the global:Element *ePtr = NULL;. Furthermore, try to get yourePtrout of the global-scope, and, check forNULLbefore you use a pointer, as withePtrin yourCreateElementmethod.