[英]Strange memory allocation in case of pointers using malloc
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a = (int *)malloc(sizeof(int));
// int a[1];
int i;
for(i = 0; i < 876; ++i)
a[i] = i;
printf("%d",a[799]);
}
即使使用malloc()
僅分配1個int的空間,此代碼也為什么起作用?
為什么此代碼有效? 即使我使用malloc僅分配1 int空間? 在這種情況下,請以不確定的行為回答。
分配4
個字節的塊,如
int *a = (int *)malloc(sizeof(int)); /* No need to cast the malloc result */
並像那樣訪問
a[i] = i; /* upto i<1 behavior is guaranteed as only 4byte allocated, not after */
導致不確定的行為,即任何事情都可能發生,並且您不應該依賴它兩次執行相同的操作。
旁注,由於malloc()
返回類型void*
及其自動安全地提升為所需類型,因此不需要強制類型轉換malloc()
的結果。 閱讀我是否強制轉換malloc的結果? 並始終檢查返回值malloc()
。 例如
int *a = malloc(sizeof(int));
if( a != NULL) {
/* allocated successfully & do_something()_with_malloced_memory() */
}
else {
/* error handling.. malloc failed */
}
它似乎正在工作。 絕對零保證它在重新編譯后或在其他環境中將以相同的方式工作。
基本上,您在這里嘗試訪問未分配給程序的內存地址(使用除0
以外的任何索引)。 因此,從您的程序角度來看,內存地址無效 。 訪問無效的內存位置會調用未定義的行為 。
正如其他人所解釋的那樣,在訪問超出分配范圍的內存區域時的行為是不確定的。 在運行內存密集型應用程序的系統上運行同一程序。 您可能會看到一個SIGSEGV。 通過Coverity靜態分析運行代碼,您將看到它捕獲了緩沖區溢出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.