简体   繁体   中英

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'. Why is this happening? even when 'malloc' assigns memory in heap.

Also if I use the same data type for both 'p' and 'arr' then no such problem occurs.

Code Output:

在此处输入图像描述

You clearly think that you've allocated an array of size 10. However when this expression is executed

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

d has a value of zero. d is a global variable so by default is initialised to zero. Confusingly there is also another variable called d in main but this has no bearing at all on the allocation of arr .

You use d 's value to decide what to pass to malloc before you set d equal to ten. 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 .

This is just the 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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