2012-10-09 37 views
0

可能重複:
determine size of dynamically allocated memory in c
newbie questions about malloc and sizeof
How can I get the size of an array from a pointer in C?如何獲得動態分配內存的大小(使用malloc或calloc)?

Malloc -> how much memory has been allocated?

int **arrofptr; 
arrofptr = (int **)malloc(sizeof(int *) * 2); 
arrofptr[0] = (int *)malloc(sizeof(int)*6144); 
arrofptr[1] = (int *)malloc(sizeof(int)*4800); 

現在我已經知道了多少字節arrofptr分配,arrofptr [0] ,arrofptr [1]?有什麼方法可以知道尺寸嗎?

如果我們將打印

sizeof(arrofptr); 
sizeof(arrofptr[0]); 
sizeof(arrofptr[1]); 

然後將打印4

+0

這是特定的實現。例如,當你在Linux內核中時,你可以通過kmalloc獲得這些信息:'stuff = kmalloc(1,GFP_KERNEL); printk(「我得到了:%zu字節的內存\ n」,ksize(stuff));'顯然只能在Linux內核中工作,您需要獲得一個與您正在使用的malloc實現綁定的答案。 – Mike

回答

2

沒有,有沒有辦法找到一個指針多少內存參照。

至少不是在任何系統上,所以沒有便攜的方式。

+0

感謝您的時間.. –

2

不可以。在不存在使用額外數據的地方存儲分配的大小。

+0

謝謝... 是的,你是對的,我們可以使用結構來跟蹤大小.... –

相關問題