-2
#include<stdio.h>

struct a
{
    void *ptr;
    unsigned long val;
};

void main()
{
    unsigned char errno;

    struct a *id;
    id = malloc(sizeof(*id));
    func2(id);
    printf("After changing %d\n", id->val);
}


void func2(struct a *id)
{
    unsigned char errno;
    func(id,&errno);
}

void func(struct a *id,void *ptr)
{   
    memset(id, 0, sizeof(*id));

    id->ptr = ptr;
    if (sizeof(id->val) >= sizeof(id->ptr))
    {   
        id->val = (unsigned long)id->ptr;
        return;
    }

}

when i am printing id->val in main function it is printing -1075050593 . But i am trying to access a invalid address. Please explain. I am very new to c programming.

shunty
  • 375
  • 2
  • 7
  • 24

2 Answers2

1

Usually, what is "accessing an invalid address"? It consists of 2 parts. 1, accessing: it includes read/write/execute. 2, invalid address: the kernel space and the un-malloced heap are the invalid address for the user application.

In this case, the address (&errno) belongs to the stack, so it is not an invalid address. And you doesn't read/write/execute the content in this address. So you are not accessing the invalid address.

BTW, with the "%d" placeholder in the printf() call, the "id->val" will be explained as a signed int type, it is why you got a negative value. Please use "%p" for pointers and "%u" for unsigned int.

Derui Si
  • 1,085
  • 1
  • 9
  • 13
0

The following statement is not attempting to access an invalid address, it is just printing the address:

printf("After changing %d\n", id->val);

what value it will hold is unknown as id is being incorrectly passed to func2().

Some problems with the code (some already mentioned in the comments):

  • incorrectly taking address of id when passing to func2() as id is already a struct a*
  • implicit declarations of memset() and malloc() as missing include directives
  • implicit declarations of func() and func2()
  • return type of main() should be int
hmjd
  • 120,187
  • 20
  • 207
  • 252
  • i made an edit instead of address of structure only pointer should be passed. printf("After changing %d\n", id->val); it trying to print a address which is invalid. – shunty Jul 12 '12 at 11:51
  • 1
    @shunty, it is just _printing_ the address value and is not attempting to access it which is fine. See http://ideone.com/ZH3Ws – hmjd Jul 12 '12 at 11:52