空指针是否可以存储比其动态分配的大小更大的数组?

我仍处于C语言的学习阶段,并编写了以下函数。我没想到它会起作用,因为void指针仅给出2个字节,这对于我的23个字节的char数组是不够的。尽管存储了char数组,但可以将其类型转换为另一个指针变量。

void main(){
     void *p = malloc(2 * sizeof(char));
     p = "Unites State of America";
     printf("%p length -> %ld, sizeof -> %ld\n", p, strlen(p), sizeof(p)/sizeof(p[0]));

     char *pstr = (char*) p;
     printf("%s length -> %ld\n", pstr, strlen(pstr));
}

结果:

0x55600dccd008 length -> 23, sizeof -> 8
Unites State of America length -> 23

我的void指针如何超过我最初要求的大小?

评论
  • 酱油王
    酱油王 回复

    You allocated 2 chars worth of memory, so now there's a small chunk of memory in the heap waiting for data to be stored there. However, you then reassign p to point to the string "Unites State of America", which is stored elsewhere. p = "string" does not move a string into the memory pointed to by p, it makes p point to the string.

  • Ula
    Ula 回复

    您的理解在这里不太正确。当您执行以下两行时,实际上是在通过不使用实际分配的动态内存来泄漏内存。

    void *p = malloc(2 * sizeof(char));
    p = "Unites State of America";
    

    Your pointer p holds a region in heap to store 2 sizeof(char) bytes but, you are actually overwriting that location with a statically allocated string. All your string operations strlen(), sizeof() are done in this statically allocated string "Unites State of America"

    You need to use functions like strncpy() or equivalent to copy the string characters to the dynamically allocated location