简体   繁体   English

指针地址被覆盖

[英]Pointer addresses are getting overwritten

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

using namespace std;
int d;
long long int *arr = (long long int*)malloc(d * sizeof(long long int));
    
int* func(){
    int *p = (int*)malloc(sizeof(int));
    *p =5;
    return p;
}

int main(){
    int *p = NULL;
    p = func();
    d =10;
    printf("add of p: %d\n\n",p);
    
    int i=0;
    for(;i<10;i++){
        printf("Add of arr: %d \n",arr+i);
    }
    
    
    return 0;   
}

The address assigned to pointer 'p' is getting overwritten by the address of some location of array 'arr'.分配给指针“p”的地址被数组“arr”的某个位置的地址覆盖。 Why is this happening?为什么会这样? even when 'malloc' assigns memory in heap.即使“malloc”在堆中分配 memory。

Also if I use the same data type for both 'p' and 'arr' then no such problem occurs.此外,如果我对“p”和“arr”使用相同的数据类型,则不会出现此类问题。

Code Output:代码 Output:

在此处输入图像描述

You clearly think that you've allocated an array of size 10. However when this expression is executed你清楚地认为你已经分配了一个大小为 10 的数组。但是当这个表达式被执行时

long long int *arr = (long long int*)malloc(d * sizeof(long long int));

d has a value of zero. d的值为零。 d is a global variable so by default is initialised to zero. d是一个全局变量,因此默认初始化为零。 Confusingly there is also another variable called d in main but this has no bearing at all on the allocation of arr .令人困惑的是, main中还有另一个名为d的变量,但这与arr的分配完全没有关系。

You use d 's value to decide what to pass to malloc before you set d equal to ten.在将d设置为 10 之前,您使用d的值来决定将什么传递给malloc Then when you do set d 's value to ten, it's a different d because you have one at global scope and one scoped inside of main .然后,当您将d的值设置为 10 时,它是一个不同的d ,因为您在全局 scope 有一个,而在main范围内有一个。

This is just the Undefined Behaviour .这只是Undefined Behaviour There are some memory-related issues (like accessing an array out of the bounds..) where C/C++ just say what should happen if everything is correctly accessed and every other thing is left undefined.有一些与内存相关的问题(比如访问越界的数组..),其中 C/C++ 只是说明如果所有内容都正确访问并且所有其他内容都未定义会发生什么。 So it may work someday or it may not.所以它可能有一天会起作用,也可能不会。

Exactly as the above answers mentioned, there is an ambiguity from your side which lead to undefined behaviour.就像上面提到的答案一样,您这边的歧义会导致未定义的行为。

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

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