I want to copy values into a struct using a pointer.
I keep getting segmentation fault from this small piece of code.
struct companyInfo
{
double sharePrice;
char companyName[100];
};
int main()
{
struct companyInfo * pdata = NULL;
strcpy(pdata->companyName, "sdfsd");
exit(0);
}
You aren’t allocating any space for the struct, just a pointer that is null.
Note:
calloc()will also zero out the memory for you, as opposed tomalloc()which will just allocate. Also, you should check the return of these functions to make sure the pointer is not NULL.Important: Any memory allocated using malloc(), calloc(), ex.. needs to be explicitly freed.
Example: