2

I was reading What is uintptr_t data type but still I'm unable to understand uintptr_t here as

  • what purpose it serve by first converting temporarily char array type to unsigned long int type and then converting back to char* type.

Consider the below code snapshot

strncpy(pCfgMgr->mGlobalCfg.grMap[index].userName,
       (char *)(uintptr_t) grParams.peerUsrName, 16); /*index is 0 */

where userName in the pCfgMgr->mGlobalCfg.grMap[index].userName is nothing but a char array declared as

char userName[MAX_USERNAME_LENGTH]; /* MAX_USERNAME_LENGTH is 16 */

And peerUsrName in the grParams.peerUsrName is also a char array declared as

char peerUsrName[16];

The thing which I didn't got is that what uintptr_t makes the difference while copying, which is nothing but alias name of unsigned long int. I am curious to know what the developer was thinking while using uintptr_t here & is it recommended ?

Though without uintptr_t above strncpy() statement produces the same output.

All helps appreciated wholeheartedly.

Achal
  • 11,821
  • 2
  • 15
  • 37
  • Using `(uintptr_t)` creates a dependency on the existence of `uintptr_t`, an optional type. Code does not compile unless the common type `uintptr_t` exist. More likely unnecessary than useful to do this. – chux - Reinstate Monica Mar 22 '19 at 22:01

1 Answers1

2

The cast is unnecessary.

The second argument to strncpy has type const char *. An expression of type char * is also valid here. grParams.peerUsrName has type char [16]. Arrays in most contexts decay to a pointer to the first element. So when you pass it to strncpy it decays to type char *, which is what it's expecting. So no need for the cast.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thanks. I agree about decaying part. I was in assumption that if user name length is just `16` or it may be hardly >100, not more in my case, why cast as `uinitptr_t`. – Achal Mar 22 '19 at 18:36
  • Any reason why dev could have gone for typecasting it to `uintptr_t`, like to avoid memory corruption ? I don't find have any clue about why `uintptr_t` needed here. – Achal Mar 22 '19 at 18:42
  • 1
    @Achal Maybe whoever wrote that code wasn't aware of the pointer decay rules. – dbush Mar 22 '19 at 18:45
  • Yes that may be the case. – Achal Mar 22 '19 at 18:47