malloc問題。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;
}
請注意,這隻有在編譯器必須盡力防止召喚惡魔時纔有可能。 – 2010-10-22 22:02:41