简体   繁体   English

如何将void指针取消引用为字符串

[英]How to dereference a void pointer as a string

I'm currently trying to copy a string to void pointer.我目前正在尝试将字符串复制到 void 指针。 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.如您所见,我正在使用 userInfo。

I've malloced the memory and used memcpy as you can see in the code below.我已经分配了内存并使用了 memcpy,如下面的代码所示。

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.我想我在将字符串复制到 void 指针时没有遇到内存问题。 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;为字符串分配空间时不要使用sizeof(char) it's always 1 unless you've something exotic going on with explicit 16-bit characters or something.它始终为 1,除非您有一些带有显式 16 位字符或其他东西的异国情调。
  2. That strlen() usage seems broken, you are adding inside the parentheses, it will call strlen() on the string minus the first character.strlen()的使用似乎坏了,你是在括号添加,它会调用strlen()上的串减去第一个字符。 If the string was empty, this will give undefined behavior.如果字符串为空,这将给出未定义的行为。 You meant strlen(ps8tmp) + 1 .你的意思是strlen(ps8tmp) + 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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