gpt4 book ai didi

c - 将 malloc() 用于双指针

转载 作者:行者123 更新时间:2023-12-01 15:54:53 25 4
gpt4 key购买 nike

一个 malloc 问题。

首先,我生成一些字符串。

其次,我为复制指向这些字符串的指针分配了非空间。此时程序可能会崩溃,因为我已经尝试将这些指针复制到任何地方,但它并没有崩溃。怎么可能?

如有任何意见,我们将不胜感激。

#include <stdio.h>

int main(int argc, char *argv[])
{
int i,
iJ,
iCharCount = 0,
iCharVal,
iStrLen = 0,
iStrNum = 50,
iStrCount = 0,
iAllocSize = 0;
char *pcStr,
*pcStr_CurPos,
**ppcStr,
**ppcStr_CurPos;

// suppose, an average length of string is * N bytes.
iAllocSize = iStrNum * 6;
iStrCount = 0;

// allocate ...
pcStr = pcStr_CurPos = (char*) malloc (iAllocSize);

if (pcStr==NULL){printf("NULL == malloc()\n"); exit (1);}

for (i=0; i < iStrNum; i++)
{
iStrCount++;
iStrLen = rand() % 7 + 2; // is in the range 2 to 8
printf("Len of Str=%d; str=[", iStrLen);
for (iJ = 0; iJ < iStrLen-1; iJ++)
{
// A-Z a-z
iCharVal = rand() % 58 + 65;

if (iCharVal > 90 && iCharVal < 97) {iJ--; continue;}

if (pcStr_CurPos < pcStr + iAllocSize )
{
printf ("%c", iCharVal);
*pcStr_CurPos++ = iCharVal;
iCharCount ++;
}
else
{
*pcStr_CurPos++ = 0;
iCharCount ++;
printf ("]\n");
goto exit;
}

}
printf ("]\n");
*pcStr_CurPos++ = 0;
iCharCount ++;
}
exit:

// I allocate NOTHING, ...
ppcStr = ppcStr_CurPos = (char**) malloc (0); // ZERO !

// Copying pointers ...
pcStr_CurPos = pcStr;
while(pcStr_CurPos < pcStr + iCharCount)
{
//... BUT IT WORKS AND DON'T CRASH.
// HOW IS IT POSSIBLE ???
*ppcStr_CurPos++ = pcStr_CurPos;
while (*pcStr_CurPos++) ;
}

ppcStr_CurPos = ppcStr;
iStrNum = iStrCount;

printf ("\n Output ppcStr:\n", iCharCount );

while(iStrNum--)
{
printf("[%d][%s]\n", iStrNum, *(ppcStr_CurPos++));
}

printf ("Press Enter key or sth\n");
getchar();
return 0;
}

最佳答案

一般来说,如果您访问未初始化的内存,C 不保证会崩溃。行为是未定义的,这意味着任何事情都可能发生。正如他们所说,编译器可以让恶魔从你的 Nose 里飞出来。

关于c - 将 malloc() 用于双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com