2016-03-21 2 views
-2

Я пытаюсь выделить пул памяти с указанным количеством байтов в памяти. когда я приступил к тестированию программы, он будет выделять только один байт за каждый пул памяти., выделяющее определенное количество байтов в памяти

typedef struct _POOL 
{ 
    int size; 
    void* memory; 

} Pool; 

Pool* allocatePool(int x); 
void freePool(Pool* pool); 
void store(Pool* pool, int offset, int size, void *object); 

int main() 
{ 

    printf("enter the number of bytes you want to allocate//>\n"); 
    int x; 
    int y; 
    Pool* p; 
    scanf("%d", &x); 
    printf("enter the number of bytes you want to allocate//>\n"); 
    scanf("%d", &x); 
    p=allocatePool(x,y); 
    return 0; 

} 



Pool* allocatePool(int x,int y) 
{ 
    static Pool p; 
    static Pool p2; 
    p.size = x; 
    p2.size=y; 
    p.memory = malloc(x); 
    p2.memory = malloc(y); 
    printf("%p\n", &p); 
    printf("%p\n", &p2); 
    return &p;//return the adress of the Pool 


} 
+0

@AnttiHaapala, даже если переменная определяется как 'static'? –

+1

Ах, извините, не видел этого. Тогда это правильно. Во всяком случае, что это значит для 'p2'; к нему, конечно, нельзя получить доступ за пределами. –

ответ

1

Бассейн может быть объявлен в основной и передается функции allocatePoll вместе с запрошенной суммы, а затем вернулся.

#include <stdio.h> 
#include <stdlib.h> 

typedef struct _POOL 
{ 
    size_t size; 
    void* memory; 
} Pool; 

Pool allocatePool(Pool in, int x); 
Pool freePool(Pool in); 

int main() 
{ 
    size_t x = 0; 
    size_t y = 0; 
    Pool p = { 0, NULL}; 
    Pool p2 = { 0, NULL}; 

    printf("enter the number of bytes you want to allocate//>\n"); 
    scanf ("%zu", &x); 
    p=allocatePool(p,x); 
    printf("%p\n", p.memory); 
    printf("enter the number of bytes you want to allocate//>\n"); 
    scanf("%zu", &y); 
    p2=allocatePool(p2,y); 
    printf("%p\n", p2.memory); 

    p = freePool (p); 
    p2 = freePool (p2); 
    return 0; 
} 

Pool freePool(Pool in) 
{ 
    free (in.memory); 
    in.memory = NULL; 
    in.size = 0; 
    return in; 
} 

Pool allocatePool(Pool in,size_t amount) 
{ 
    in.size = amount; 
    if ((in.memory = malloc(amount)) == NULL && amount != 0) { 
     printf ("Could not allocate memory\n"); 
     in.size = 0; 
     return in; 
    } 
    printf("%p\n", in.memory); 
    return in;//return Pool 
} 
Смежные вопросы