Hamza Mohamed Hamza
Hamza Mohamed Hamza

Reputation: 67

Using memset or strtok without initializing

char *tokens[100];  

memset(tokens,'\0',sizeof(tokens));  

tokens[n]=strtok(tempVar,",");

Is this code valid? I think memset is filling a random place of memory right ?

Upvotes: 0

Views: 263

Answers (4)

netcoder
netcoder

Reputation: 67685

It is valid code (well except that n is undefined in the example).

memset like this is initializing. You're zeroing out the whole tokens variable. It is not a random location. It is not mandatory in your example, either.

Also, take note that strtok does not return a copy of the token, but rather modifies tempVar and returns pointers to its elements. If tempVar goes out of scope, the memory locations pointed by the tokens elements will become dangling pointers, and dereferencing them will invoke undefined behavior.

Upvotes: 1

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70931

I would re-write the memset bit as:

memset(tokens, 0, sizeof(tokens));  

Because what you do is actually assign zero to all the pointers in the array. Otherwise the code is valid, but I am not sure it does what you expect.

Upvotes: 1

unwind
unwind

Reputation: 399703

It is valid, but not very useful since the result of setting a bunch of pointers to all-bits-zero is not well defined. There's no guarantee that a NULL pointer looks (in memory) as "all bits zero", so it's bad practice.

And no, this is not filling "random" memory, it's filling exactly the memory occupied by the tokens array.

Upvotes: 3

parkydr
parkydr

Reputation: 7784

It will clear tokens which is an array of 100 pointers, not the memory pointed to by those pointers.

Upvotes: 2

Related Questions