user1611830
user1611830

Reputation: 4867

Pointer error message

I apologize by advance if my question seems absolutely trivial, but I don't understand why if I run

int main(){
    int *count = 0;
    printf("%d",*count);
}

I have no input (using Xcode) and an error:

Thread 1 : EXC_BAD_ACCESS(code=1, address = 0x0)

Could someone explain to me what this is?

Upvotes: 1

Views: 250

Answers (2)

K Scott Piel
K Scott Piel

Reputation: 4380

You have declared count as a pointer to an integer value not as an integer value and you have initialized the pointer to be NULL (memory address 0).

You would want to do the following...

int main()
{
   int buffer = 0;
   int* count = &buffer;
   printf( "var %d = %d\n", buffer, *count );
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726929

What happens is dereferencing a null pointer, which is undefined behavior: your count is a pointer, which means that it needs to point to a valid location before you can read from it:

int main(){
    int *count = malloc(sizeof(int)); // Give your pointer a valid location
    *count = 123;                     // This is valid now
    printf("%d", *count);             // prints 123
    free(count);                      // Don't forget to free allocated memory
}

Upvotes: 3

Related Questions