[英]Return value 3221225725, possible buffer overflow?
练习的目的是分配维数从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;
}
问题在这里。
*p2 = (int*)malloc(i*sizeof(int)); //allocating the space for the pointers
您想创建一个“数组数组”,这就是为什么要使用双指针的原因。 int** p2
是一个指向int*
的指针的数组, 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
这应该可以按预期工作。 就个人而言,我会在循环中使用i
和i+2
,但是您的选择很好。
请注意,您不需要free
分配的内存。 程序结束时,它消失了。 如果您的分配需要free
空间,那么您需要编写另一个循环来释放每个p2[i]
数组中的内存,然后释放p2
。
同样,从malloc()
返回值也被认为是一个坏主意 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.