使用malloc()作为双指针

Bob*_*Bob 2 c string malloc pointers

一个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;
}
Run Code Online (Sandbox Code Playgroud)

nov*_*lis 9

通常,如果访问未初始化的内存,则无法保证C崩溃.行为未定义,这意味着任何事情都可能发生.正如他们所说,编译器可以让恶魔飞出你的鼻子.