简体   繁体   中英

passing a struct pointer to a function segfault C FREEBSD

I am trying to port my C GNU/Linux code to FreeBSD. At first I thought it wouldn't compile and act abnormally, but it didn't act up on me because it didn't use functions that the other OS does not have native to it. Although it compiles fine (no errors or warnings using -Wall ) the application keeps seg faulting on a line that works normally as intended on a GNU/Linux install.

What I am doing is creating a pointer to a struct and then passing the pointer to a function as a void pointer and then recreating it inside the function.

ex:

typedef struct
{
   int i;
}some_struct;

int main()
{
   some_struct *test = malloc(sizeof(some_struct));
   test->i = -1;
   function(test);

return 0;
}

void *function(void *prarm)
{
   some_struct test = *((some_struct *)param);  //segfaults on this line.
   free(param);


return NULL;
}

On my GNU/Linux install this would allow me to recreate the struct with the passed pointer data locally inside the function and allow me to free the malloc ed memory from main() but on FreeBSD it seg faults and I do not know why.

If I break at function in gdb and type

p *(some_struct *)param

It successfully prints out my command struct that is created from the pointer and all its variables from inside the function.

Im at a lost at why this is working GNU/Linux and seg faulting on my FreeBSD test machine.

Thanks for any help towards this problem I am having.

It's weird that this would fail. Have you tried re-ordering the functions or declaring function before use (before main):

void *function(void *prarm);

You are creating a very large stack frame:

char buff[3000600], data[3000000], url[1024], c[1];

That's almost 6MB - perhaps you are exceeding the default process stack size limit on FreeBSD? FreeBSD uses SIGSEGV to kill a process that exceeds this limit, and it would be detected when you write to a local variable that would cause the stack to be extended beyond the limit. You can tweak the stack size limit in login.conf .

I don't see any reason for it to segfault, especially if -Wall is silent.

One thing that bothers me about this is that there is no apparent declaration in effect for function() at the point of the call in main() . Without a declaration, C assumes the parameter is passed as an integer, and so should give a warning. You could fix this in several ways—add a function declaration above main(), move the function definition above main, or put the declaration in a header file included before main().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM