I get a segfault when trying to memset
an array of chars that was allocated statically, but not for an array of the same length that was allocated using malloc
.
variable definitions:
//static
char inBuff[IN_BUFF_LEN];
//dynamic
char * inBuffD;
function call:
//static, cast used because char** != char (*) [n]
serverInit(portNum, (char**) &inBuff, &serv_addr, &sockfd)
//dynamic
serverInit(portNum, &inBuffD, &serv_addr, &sockfd)
use within the function:
memset(*inBuffAdr, 0, IN_BUFF_LEN);
I suspect that my problem is in the difference of the function calls, or to be more precise, my incomplete understanding of the "char** != char (*) [n]" situation. But I have been banging at this for too long and can't see the forest from the trees so any hints and advice would be very appreciated.
只需发送inBuff(不是** inBuff),然后发送memset inBuffAdr而不是* inBufAdr(您的其他memset可能也不起作用,您只是还不知道)
Why do you need to pass a double-pointer to your serverInit()
function? If the function can modify where the pointer points to, then you can't pass a statically allocated array. If the function can't modify where the pointer points to, then you don't need a double-pointer.
The type of &inBuff
is pointer to array of char
of size IN_BUFF_LEN
, which is quite distinct from a char **
. You've bludgeoned the compiler into not complaining, claiming that you know better than the compiler what you're doing. Don't use a cast like that unless you are sure you do know more than the compiler.
Frankly, given the current prototype, you'd probably be best off with:
//static
char inBuff[IN_BUFF_LEN];
char *inBuffS = inBuff;
//dynamic
char *inBuffD;
serverInit(portNum, &inBuffS, &serv_addr, &sockfd);
However, I'm deeply suspicious that you should revise serverInit()
to take a simple char *
instead of char **
for the second argument.
Why not define serverInit()
the following way:
serverInit(...., char * inBuff, ....)
then call it
serverInit(...., inBuff, ....)
and then inside serverInit()
call memset()
like this:
memset(inBuff, 0, IN_BUFF_LEN);
Part of your confusion is in thinking that &inBuff
can be dereferenced to get inBuff
. If you run this simple test program:
#include <stdio.h>
char inBuff[1000];
int main( int argc, char *argv[])
{
printf( "%p %p\n", inBuff, &inBuff);
return 0;
}
You'll see that it prints the same address for both notations. If you try to dereference &inBuff
, you'll be taking the first few bytes of the array as an address.
As others have stated, you should just be passing a pointer to the memory you're going to set. Hopefully this answer will help you with future debugging sessions.
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.