문제

I don't think I'm understanding something here...

bool (*lookup)[100];
memset(lookup, 0, 100 * sizeof(*lookup));

I'm trying to initialize a pointer to a stack allocated array (the pointer will only be passed to calls within the stack frame). The memset is for initializing the array to 0's.

The previous code causes a segfault, does memset not like pointers?

도움이 되었습니까?

해결책

By doing

memset(lookup, 0, 100 * sizeof *lookup);

you do not "initialize a pointer" but the memory the pointer lookup points to.

And most probably you did not made the pointer point to some valid memory, prior to calling memset(), so writing to random memory invokes undefined behaviour, which crashes the program.

There are several way to get valid memory.

Get it from the stack like so:

bool lookup_instance[100] = {0};
bool (*lookup)[100] = &lookup_instance;
/* No need to memset it to 0s as this had been done by ... = {0} already. */

or get it yourself like so:

bool (*lookup)[100] = malloc(sizeof *lookup);
if (NULL == lookup) 
{
  perror("malloc() failed"):
}
else
{
  memset(lookup, 0, sizeof *lookup);
}

The shortest solution would be:

bool (*lookup)[100] = calloc(1, sizeof *lookup);
if (NULL == lookup) 
{
  perror("calloc() failed");
}
else
{
  /* No need to memset it to 0s as this has been done by calloc() already. */
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top