分配指向malloc保留的块的指针

时间:2013-11-04 12:57:24

标签: c malloc

基于这个答案:https://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;
}

p->arr1分配到(p + 1)的地址

是安全的
p->arr1 = (int *)(p + 1);

1 个答案:

答案 0 :(得分:-1)

您在考虑结构分配方面存在根本问题。 当malloc一个struct,你malloc那个struct的sizeof时,你不会为它将包含的数组malloc,那些需要单独分配。为此,您的代码应该更像:

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;
}

请记住,当你释放它时,你需要单独释放数组,所以如果指针myStruct是a

free( a->arr1 );
free( a->arr2 );
free( a );