分配指针来阻止使用malloc保留 [英] Assign pointer to block reserved with malloc
问题描述
根据这样的回答:<一href=\"http://stackoverflow.com/a/19765782/1606345\">http://stackoverflow.com/a/19765782/1606345
的#include&LT;&stdlib.h中GT;typedef结构{
INT * ARR1;
INT * ARR2;
} MYSTRUCT;MYSTRUCT * allocMyStruct(INT NUM)
{
MYSTRUCT * P; 如果((P =的malloc(sizeof的* P +
10 * sizeof的* P-&GT; ARR1 +
10 * NUM * sizeof的* P-&GT;!ARR2))= NULL)
{
对 - &GT; ARR1 =为(int *)(P + 1);
P-&GT; ARR2 = P-&GT; ARR1 + 10;
}
回磷;
}无效initMyStruct(MYSTRUCT *一,INT NUM)
{
INT I; 对于(I = 0; I&小于10;我++)A-&GT; ARR1 [I] = 0;
对于(I = 0; I&小于10 *民;我++)A-&GT; ARR2 [I] = -1;
}INT主要(无效)
{
INT NUM = 3; MYSTRUCT * A = allocMyStruct(NUM);
initMyStruct(一,NUM);
自由(一);
返回1;
}
这是安全的分配 P-&GT; ARR1
来的(P + 1)
<地址? / p>
P-GT&; ARR1 =(INT *)(P + 1);
您在你是如何考虑结构分配在这里有一个根本性的问题。
当你的malloc一个结构,你的malloc的结构,你不为的malloc它将包含数组,这些需要单独分配的sizeof。要做到这一点您的code应该看起来更像是:
MYSTRUCT * allocMyStruct(INT NUM)
{
MYSTRUCT * P =的malloc(sizeof的(MYSTRUCT)); 如果(P!= NULL)
{
P-&GT; ARR1 =的malloc(sizeof的(INT)* 10); //对 - &GT; ARR1现在指向10个元素的阵列
P-&GT; ARR2 =的malloc(sizeof的(INT)* 10 * NUM); //对 - &GT; ARR2现在指向10 * NUM元素的数组
}
回磷;
}
请记住,当你这个,你需要释放阵列单独以及因此,如果您的指针MYSTRUCT是 A
:
免费(A-&GT; ARR1);
免费(A-&GT; ARR2);
自由(一);
Based on this answer: http://stackoverflow.com/a/19765782/1606345
#include <stdlib.h>
typedef struct {
int *arr1;
int *arr2;
} myStruct;
myStruct *allocMyStruct(int num)
{
myStruct *p;
if ((p = malloc(sizeof *p +
10 * sizeof *p->arr1 +
10 * num * sizeof *p->arr2)) != NULL)
{
p->arr1 = (int *)(p + 1);
p->arr2 = p->arr1 + 10;
}
return p;
}
void initMyStruct(myStruct * a, int num)
{
int i;
for (i = 0; i < 10; i++) a->arr1[i] = 0;
for (i = 0; i < 10 * num; i++) a->arr2[i] = -1;
}
int main (void)
{
int num = 3;
myStruct *a = allocMyStruct(num);
initMyStruct(a, num);
free(a);
return 1;
}
It is safe to assign p->arr1
to the address of (p + 1)
?
p->arr1 = (int *)(p + 1);
You have a fundamental problem here in how you are thinking about struct allocation. When you malloc a struct, you malloc the sizeof that struct, you don't malloc for the arrays it will contain, those need to be allocated separately. To do this your code should look more like:
myStruct *allocMyStruct(int num)
{
myStruct *p = malloc( sizeof( myStruct ) );
if( p != NULL )
{
p->arr1 = malloc( sizeof( int ) * 10 ); // p->arr1 now points to an array of 10 elements
p->arr2 = malloc( sizeof( int ) * 10 * num ); // p->arr2 now points to an array of 10 * num elements
}
return p;
}
Keep in mind when you free this you will need to free the arrays individually as well so if your pointer the myStruct was a
:
free( a->arr1 );
free( a->arr2 );
free( a );
这篇关于分配指针来阻止使用malloc保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!