2

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?

3
  • 1
    Where is the "stack allocated array"? Commented Oct 21, 2013 at 15:59
  • memset likes pointers just fine; and if you were invoking it on the memory occupied by the pointer, memset(&loopkup, 0, sizeof(lookup)); the code would be valid (albeit somewhat pointless). As written, you're invoking it with an indeterminate address retrieved from an uninitialized pointer variable, and this is therefore undefined behavior. Commented Oct 21, 2013 at 16:05
  • The size passed to memset must be consistent with the object the pointer points to. The posted code has undefined behavior because the pointer is uninitialized, otherwise post the code that initializes the pointer. Commented May 8, 2019 at 5:18

1 Answer 1

6

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. */
}
Sign up to request clarification or add additional context in comments.

5 Comments

But the 100* makes no sense, because sizeof already gets the size of the array, not the member.
@rodrigo: Huu .. did I wrote that? Must have been a temporary brain laps ... thanks anyway! Corrected!
@rodrigo: Ah, got it, I copied that from the OP. Damn copy&paste programming ... :}
I was under the impression that bool (*lookup)[100]; allocates an array and returns a pointer to its first element.
@jab: no, it's a pointer variable, where the pointed-to type is bool[100].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.