简体   繁体   English

在使用malloc的指针的情况下进行奇怪的内存分配

[英]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]);
}

Why is this code working, even if, I am allocating only 1 int's space using malloc() ? 即使使用malloc()仅分配1个int的空间,此代码也为什么起作用?

Why is this code working? 为什么此代码有效? Even if, I am allocating only 1 int's space using malloc ? 即使我使用malloc仅分配1 int空间? In such case answer in undefined behavior. 在这种情况下,请以不确定的行为回答。

Allocating block of 4 bytes like 分配4个字节的块,如

  int *a = (int *)malloc(sizeof(int)); /* No need to cast the malloc result  */

and accessing beyond that like 并像那样访问

a[i] = i; /* upto i<1 behavior is guaranteed as only 4byte allocated, not after */

results in undefined behavior ie anything can happen and you shouldn't depend on it doing the same thing twice. 导致不确定的行为,即任何事情都可能发生,并且您不应该依赖它两次执行相同的操作。

Side note, type casting the result of malloc() is not required as malloc() return type void* & its automatically promoted safely into required type. 旁注,由于malloc()返回类型void*及其自动安全地提升为所需类型,因此不需要强制类型转换malloc()的结果。 Read Do I cast the result of malloc? 阅读我是否强制转换malloc的结果? And always check the return value malloc() . 并始终检查返回值malloc() for eg 例如

int *a = malloc(sizeof(int));
if( a != NULL) {
   /* allocated successfully & do_something()_with_malloced_memory() */ 
}
else {
    /* error handling.. malloc failed */ 
}

It seems to be working. 似乎正在工作。 There is absolutely zero guarantee it will work the same way after a recompile, or in a different environment. 绝对保证它在重新编译后或在其他环境中将以相同的方式工作。

Basically, here you're trying to access memory address, which is not allocated to your program (using any index other than 0 ). 基本上,您在这里尝试访问未分配给程序的内存地址(使用除0以外的任何索引)。 So, from your program point of view, the memory address is invalid . 因此,从您的程序角度来看,内存地址无效 Accessing invalid memory location invokes undefined behaviour . 访问无效的内存位置会调用未定义的行为

As others have explained, the behavior while accessing a memory region beyond what is allocated, is undefined. 正如其他人所解释的那样,在访问超出分配范围的内存区域时的行为是不确定的。 Run the same program on a system which is running memory intensive applications. 在运行内存密集型应用程序的系统上运行同一程序。 You might see a SIGSEGV. 您可能会看到一个SIGSEGV。 Run your code through coverity static analysis and you will see it catching the buffer overrun. 通过Coverity静态分析运行代码,您将看到它捕获了缓冲区溢出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM