Question:
ANSI-C, Structs, Pointers and Segfaults. HELP!?
Talha A. B.
2010-09-03 13:19:16 UTC
I've been experimenting a little with C lately, and I've been having some trouble compiling this code:


#include
#include
#include

struct myStruct
{
char message[10];
int (*hello)(struct myStruct *self);
};

int hello(struct myStruct *self)
{
printf("%s\n", self->message);
return 0;
}

int main()
{
struct myStruct *frodo;

printf("START\n");
frodo = malloc(sizeof(*frodo));
frodo->hello = hello;
strcpy(frodo->message, "printing message");
/* Line A */ frodo->hello(frodo);

/* Line B */ hello(frodo);

free(frodo);
printf("END\n");

return 0;
}

Now the line marked Line A is the problem. For some reason the program always segfaults at that point, even though Line B works just fine. Also, this problem only occurs when i use dynamic memory allocation. If I declare a normal myStruct variable, and assign the values to it, it works just fine. Any ideas what I'm doing wrong?
Three answers:
Ratchetr
2010-09-03 13:28:01 UTC
You only allocated 10 bytes for message in myStruct.

The largest string you can strcpy into that buffer is 9 characters (10'th will be used for the nul terminator).



printing message is longer than that, so it will overwrite the value you stored in hello. Now it is no longer a function pointer, but a bit of the string. The segfault occurs because the characters are treated as the function address.
ostos
2016-12-11 18:51:36 UTC
The order wherein functionality arguements are parsed are implementation based. I this occasion that's executing the printf arguments backward. you will see that this habit in case you're disposing of the final *(pf++) interior the 2nd printf. this could yield 0.5, 0.4. So the actual answer is it has not something to do with rules and each thing to do with the implementation of C you're using.
Erika
2016-12-10 14:59:46 UTC
The order wherein function arguements are parsed are implementation based. I this occasion that's executing the printf arguments backward. you will discover this habit in case you're disposing of the final *(pf++) interior the 2nd printf. this would yield 0.5, 0.4. So the genuine answer is it has no longer something to do with tips and each thing to do with the implementation of C you're utilising.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...