[英]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:有两个问题:
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.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.strlen(ps8tmp) + 1
.strlen(ps8tmp) + 1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.