I'm working on a project and I keep getting segmentation faults, and the values of the structs aren't being passed. Figuring out why is driving my crazy. I've tried figuring out the problem with simpler programs, and I think I've found the problem, but I'm not sure how to fix it.
The problem is that when I "malloc" a struct, THEN pass by value, the value is lost. Adding "free" later produces a segmentation fault. I'm not trying to access a value from before the "malloc()" or after the "free()", so I'm confused as to why this is happening.
Here's a simple model of the problem:
#include <stdlib.h>
#include <stdio.h>
struct structexample
{
int element;
};
void initStruct(struct structexample * teststruct, int * number)
{
teststruct = malloc(sizeof(struct structexample));
teststruct->element = 10;
printf("teststruct element is %d in initStruct\n", teststruct->element);
*number = 5;
}
void printtest(struct structexample * teststruct, int * number)
{
printf("teststruct element is %d in printtest\n", teststruct->element);
printf("Number is %d\n", *number);
free(teststruct);
}
int main()
{
int number;
struct structexample teststruct;
initStruct(&teststruct, &number);
printtest(&teststruct, &number);
printf("teststruct element is %d in main()", teststruct.element);
return 0;
}
This produces:
teststruct element is 10 in initStruct
teststruct element is -7967792 in printtest
Number is 5
Segmentation fault
I compile the program with "gcc -Wall -pedantic -ansi" and get no errors or warnings there.
When I comment out "malloc" and "free" it correctly produces:
teststruct element is 10 in initStruct
teststruct element is 10 in printtest
Number is 5
If I only comment out "free" but leave "malloc" in, that fixes the segmentation fault, but the values of the structs are still incorrect. In this simple program I don't really need "malloc()" and "free()", but I do need them in my larger project. If I can make them work in this simpler program, then I think I can fix the larger one. I can't find a similar problem on Google unfortunately.