返回值3221225725,可能的缓冲区溢出?

时间:2014-11-08 23:45:10

标签: c arrays pointers

练习的目的是分配尺寸从2到n + 1的“n”数组,并为每个数组的每个元素赋予它们随机值 所以我的想法是使用指针的双指针(可以在某种程度上被视为数组(?))抱歉意大利语,但它是我学校的练习 无论如何,代码似乎是正确的,但它不能超过2个循环,例如它适用于n = 1,2但是从3开始退出循环并终止程序,任何避免它的建议或者?

以下是代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100

/*The aim of the exercise is to allocate "n" arrays whose dimensions goes from 2 to n+1 and give them random values to each element of each array
So my idea was to use double pointers to pointers (that can be considered arrays in some way (?) ) Sorry for the italian language but it's an exercise for my school
Anyhow, the code seems teorically correct but it can't do more than 2 cycles, for example it works for n=1,2 but from 3 and on it quits from the cycle and terminates the program, any suggestions?*/

int main() {
        int n, i, j = 0, array[MAX];
        int *p1 = NULL, **p2 = NULL;
        srand(time(NULL));
        printf("Inserisci un numero naturale n per allocare un numero n di vettori\ndi lunghezza da 2 a n+1 :\n"); //Write a natural number n to allocate n arrays which contains from 2 to n+1 elements
        scanf("%d", &n);
        printf("\n\n");
        p2 = (int**)malloc(n*sizeof(int*)); //allocating the space for a double pointer
        for (i = 2; i <= n+1; i++) {
                *p2 = (int*)malloc(i*sizeof(int)); //allocating the space for the pointers
                printf("\nVettore #%d = ", i-1);
                for (j = 0 ;j < i ;j++) {
                        p2[i-2][j] = rand() % 10;
                        printf("%d ", p2[i-2][j]);

                }
                free(*p2);
        }



return 0;


}

1 个答案:

答案 0 :(得分:0)

问题出在这里。

*p2 = (int*)malloc(i*sizeof(int)); //allocating the space for the pointers

你想制作一个&#34;阵列数组,&#34;这就是你使用双指针的原因。 int** p2是指向int*指针的数组,指针是整数。

所以这看起来不错:

p2 = (int**)malloc(n*sizeof(int*)); //allocating space for an array of pointers

这是一个指向int*的n个指针的数组。现在我们希望这些指针中的每一个都指向数组。在for循环中,使用

p2[i-2] = (int*)malloc(i*sizeof(int)); //allocating space for one array

这应该按预期工作。就个人而言,我会在我的循环中使用ii+2,但您的选择很好。

请注意,您不需要free已分配的内存。程序结束时它会消失。如果您的作业需要free空格,那么您需要编写另一个循环来释放每个p2[i]数组中的内存,然后释放p2

此外,从malloc()转换返回值被视为bad idea