简体   繁体   中英

How to dereference a void pointer as a string

I'm currently trying to copy a string to void pointer. Here is a struct of void pointer that I'm using.

typedef struct
  {
  struct runtime_type *runtimeTypeHead; /* Array of Runtime Types       */
  ST_INT numRuntimeTypes;               /* # of Runtime Types in array  */
  ST_CHAR *dataBuf;                     /* ptr to local data            */
  ST_VOID *userInfo;                    /* To store anything user wants.*/
                                        /* GSE code does not use it.    */
  } GSE_IEC_DATA_ENTRY;

And I'm using userInfo as you can see.

I've malloced the memory and used memcpy as you can see in the code below.

DataEntry->userInfo = safe_malloc(sizeof(ST_CHAR)*strlen(ps8tmp+1));
memcpy((ST_CHAR*)DataEntry->userInfo, ps8tmp,strlen(ps8tmp));

I think I didn't encounter a memory problem when I copy a string to the void pointer. Then, I am having a seg fault when I try to print the copied string as below.

printf("Updated DataEntry : %s\n", *(ST_CHAR*) DataEntry->userInfo);

Can anyone point out that why I'm having a segfault when I simply printing the string?

This:

DataEntry->userInfo = safe_malloc(sizeof(ST_CHAR)*strlen(ps8tmp+1));

has two problems:

  1. Don't use sizeof(char) when allocating room for strings; it's always 1 unless you've something exotic going on with explicit 16-bit characters or something.
  2. That strlen() usage seems broken, you are adding inside the parentheses, it will call strlen() on the string minus the first character. If the string was empty, this will give undefined behavior. You meant strlen(ps8tmp) + 1 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM