Question Details

No question body available.

Tags

c string pointers memory-management

Answers (2)

July 27, 2026 Score: 2 Rep: 235,454 Quality: Medium Completeness: 80%

Your code has undefined behavior as a result of a NULL pointer dereference.

The variable thedata is an array of struct pointers. Because it is declared at file scope without an initializer, the members of the array are initialized to NULL. When you then do this assignment:

thedata[index]->mychar=
        malloc(sizeof(pstring)+1);

The implicit dereference in the -> operator then dereferences that NULL pointer, giving rise to undefined behavior.

Also, the above call to malloc isn't allocating the correct amount of space. Since pstring is a pointer to char, the sizeof operator gives you the size of that pointer (likely either 4 or 8) instead of the length of the string it points to. In your particular case it happens to work since the string "test" contains 4 bytes (not including the terminating null character), however using a larger string would result in the string being truncated when copied.

So there's two things to fix here.

First, you don't really need an array of pointers. An array of structs will do what you want. Second, you should instead use strlen(pstring) instead of sizeof(pstring) to get the proper string length.

typedef struct mystruct
{
    char *mychar;
}
pmystruct;    // No pointer hidden behind a typedef

pmystruct thedata[2];

void insert(char *pstring, int index) { thedata[index].mychar= malloc(strlen(pstring)+1); // use strlen instead of sizeof strlcpy ( thedata[index].mychar, pstring, strlen(pstring)+1 // use strlen instead of sizeof ); }

int main() { insert("test", 0); printf("%s\n", thedata[0].mychar); free(thedata[0].mychar); return 0; }
July 27, 2026 Score: 1 Rep: 11 Quality: Low Completeness: 40%

sizeof(pstring) is the size of a pointer not string. (thedata[index]->mychar)=ouputs undefined behavior due to segfault

pmystruct the_data[2]; declares an array of uninitialized pointers.