C 我以为有内存入侵问题,对吗?

C 我以为有内存入侵问题,对吗?,c,malloc,heap-memory,C,Malloc,Heap Memory,我的代码如下: int *text(char *str) { int *cond; int *temp; int cond_size; int num; int i; cond_size = -1; cond = malloc(sizeof(int) * 1); *cond = 0; while (*str != '\0') { if (*str ==

我的代码如下:

int     *text(char *str)
{
    int     *cond;
    int     *temp;
    int     cond_size;
    int     num;
    int     i;

    cond_size = -1;
    cond = malloc(sizeof(int) * 1);
    *cond = 0;
    while (*str != '\0')
    {
        if (*str == ' ')
            str++;
        num = 0;
        while (*str >= '0' && *str <= '9')
            num = num * 10 + *(str++) - '0';
        temp = cond;
        cond = malloc(sizeof(int) * (++cond_size));
        i = -1;
        while (++i < cond_size)
            cond[i] = temp[i];
        cond[i] = num;
        free(temp);
    }
    g_size = (i + 1) / 4;
    return (cond);
}

但是,当我检查(时,我可以看到一些问题:

  • 条件大小为-1:

    cond_size = -1; // Here is problem
    cond = malloc(sizeof(int) * 1);
    *cond = 0;
    while (*str != '\0')
    {
        if (*str == ' ')
            str++;
        num = 0;
        while (*str >= '0' && *str <= '9')
           num = num * 10 + *(str++) - '0';
        temp = cond;
        cond = malloc(sizeof(int) * (++cond_size)); // you are trying allocate memory with size 0
        i = -1;
        while (++i < cond_size)
            cond[i] = temp[i];
        cond[i] = num; // you are writing to not allocated memory
    
    cond_size=-1;//问题出在这里
    cond=malloc(sizeof(int)*1);
    *cond=0;
    而(*str!='\0')
    {
    如果(*str=='')
    str++;
    num=0;
    
    虽然(*STR>=‘0’& & STR在您的代码中有一些奇怪的东西:例如,为什么在分配了堆区域MALLC的地址之后,您就有了<代码> *COND=0 < /Cord>行?第一个Malc内存将丢失。您也可以考虑检查MALOC的Runun值,而不是自己做。”但愿我帮助过你。
    ==============
    |  4 3 2 1   |
    |4        '1'| <==
    |3         2 |  
    |2         2 |
    |1         2 |
    |  1 2 2 2   |
    ==============
    
    cond_size = -1; // Here is problem
    cond = malloc(sizeof(int) * 1);
    *cond = 0;
    while (*str != '\0')
    {
        if (*str == ' ')
            str++;
        num = 0;
        while (*str >= '0' && *str <= '9')
           num = num * 10 + *(str++) - '0';
        temp = cond;
        cond = malloc(sizeof(int) * (++cond_size)); // you are trying allocate memory with size 0
        i = -1;
        while (++i < cond_size)
            cond[i] = temp[i];
        cond[i] = num; // you are writing to not allocated memory
    
    temp = cond;
    cond = malloc(sizeof(int) * (++cond_size));
    i = -1;
    while (++i < cond_size)
        cond[i] = temp[i]; // temp size is cond_size-1