memory and function pointer problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi All,
        I am allocating some bytes using malloc(), but
I am able to access the memory beyond what I was
allocated. Below is the program which I ran,

int main() {
    int *p;
    int i;
   
    p = malloc(500*sizeof(int));
    for(i=0;i<512;i++) {
        p[i] = i;
    }
    for(i=0;i<512;i++) {
        printf("p[%d]: %d\n",i,p[i]);
    }
    return 0;
}

Its giving this output:
[root@ne prog]# ./mall
p[1]: 1
p[2]: 2
p[3]: 3
p[4]: 4
....<snip>....
p[507]: 507
p[508]: 508
p[509]: 509
p[510]: 510
p[511]: 511       <--- It is able to access the
memory.

Can someone please explain why this is happening.I am using gcc4 compiler on 2.6 linux kernel. Shouldn't it give seg fault. I read that accessing more memory than allocated results in seg fault. If I am not getting seg fault here, then in which case I should expect it ? Also, When I do something like this,
int *p;
int i = 1; // located on stack
p = &i; //pointing to stack memory
 and then when I try to write at some other memory using p by decrementing/incrementing then it gives seg fault (but in this case reading doesn't). malloc() gives memory from heap. So does this mean that we can write to any location in heap and it doesn't matter whether it is allocated to your process or not. Will it not corrupt the data for other process using heap mem.
Please explain this.

Another problem I am getting is in this program,
int func() {
        return 0;
}
                                                     
                                           
int main() {
        int func();
        int (*fun)();
        fun = func;
        printf("%d, %p, %d, %p\n",sizeof(func),func,sizeof(fun),fun);
        return 0;
}

The output I am getting is,
1, 0x4004a8, 8, 0x4004a8

shouldn't I get same value at 1st and 3rd ?

If we just write func, it will give the address of func(), isn't it ? then why sizeof(func) is giving 1 and not 4 bytes. Also as fun points to address of func(), then why its giving 8 bytes and not 4.

Please explain this. Am I doing something wrong in these prog ?

thanks,
GS

[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux