使用realloc时堆积损坏 - VS 2010

时间:2011-11-27 04:26:02

标签: realloc

所以我的prgrm工作正常,直到我试图重新分配一个指针,但它并没有一直崩溃。有时它确实如此,有时它运行得很好。有人请告诉我我的代码有什么问题吗?

#include <stdio.h>
#include <cstdlib>
#include <cstring>

char getword(char[]); //return length

int main()
{   

    static char buffer[100];
    int wcount = 5, n = 0;
    char **p = (char**) malloc (wcount);
    int len = getword(buffer);
    while (len && n < wcount)
    {
        p[n] = (char *) malloc (len);
        strncpy(p[n++], buffer, len);
        len = getword(buffer);
        if (n == wcount)
        {
            wcount += 10;
            char** temp = (char**) realloc (p, wcount);
            if (temp == NULL)
                break;
            else
                p = temp;
        }
    }

    return 0;
}

char getword(char buffer[])
{
    int len = 0;
    char c = getchar();

    if (c == EOF)
        return len;

    while (c == 32 || c == '\n' || c == '\t' || c == '\v')
    {
        c = getchar();
    }
    do
    {
        buffer[len++] = c;
        c = getchar();
    }
    while (c != 32 && c != '\n' && c != '\t' && c != '\v' && c != EOF);
    buffer[len] = 0;
    return ++len;
}

1 个答案:

答案 0 :(得分:2)

char **p = (char**) malloc (wcount);分配wcount个字节,而不是wcount个指针。同样realloc