PDA

View Full Version : C: Simple pointers use. EXC_BAD_ACCESS - I am lost.


mstac
07-12-2007, 02:27 AM
Hi all,
I am quite a newbie to macosxhints forum, so I hope I'm in the right category, and my post is relevant.
I'm having problem with some very basic C code, and I really don't understand why.

this code gives me a EXC_BAD_ACCESS:

#include <stdio.h>
int main (int argc, const char * argv[]) {
int* a; int* b;
*a =10;
printf("Hello, World!\n");
return 0;
}


The problem comes when I add the int*b, ie this works

#include <stdio.h>
int main (int argc, const char * argv[]) {
int* a;
*a =10;
printf("Hello, World!\n");
return 0;
}


Actually, even this works:

#include <stdio.h>
int main (int argc, const char * argv[]) {
int* a;int* b;
printf("Hello, World!\n");
return 0;
}

From the debugger, it looks like when I creat a second int pointer, the first one gets the address "0x0", in which I can't write. If I had 3 pointers, the first 2 ones would get this "0x0" address... declaring the second pointer after I assigned a value to *a does not change anything.

I'm very confused,it looks like I can only use one integer pointer in my program... Please help me!
thank you,
Martin

PS: It's not a compiling error, everything compiles well. It's just when I execute my code, I get a EXC_BAD_ACCESS error.
PS2: I'm using Xcode on MacOS 10.4.10.

mstac
07-12-2007, 03:51 AM
Got some help from a computer scientist...

Actually, this shouldn't work:
#include <stdio.h>
int main (int argc, const char * argv[]) {
int* a;
*a =10;
printf("Hello, World!\n");
return 0;
}

That's why I was confused. Creating a pointer doesn't creat a space to write someting in memory, it's just a pointer with some random value.

Hope this post can at least help someone thanks to google ;-).

Sorry I had to post something I should have read in C 101.

EatsWithFingers
07-17-2007, 06:27 AM
Creating a pointer doesn't creat a space to write someting in memory, it's just a pointer with some random value.
Exactly. The variable a is only a pointer (i.e. a memory location - or an unsigned integer, depending on how you view such things). There are two ways to proceed:

int* a = malloc(sizeof(int));
*a = 10;
This will reserve memory, so you can assign a value to *a. Just remember to ensure that a is not NULL before assigning to it, and to free the allocated space when you're done with it.

int a = 10;
int* addr = &a;
Alternatively, you can make a an integer, and use &a when the memory address is required. This works because non-malloc()'d variables are stored in memory addresses corresponding to the program's heap (so the variables are actually addressable). However, such variables only exist while they are in scope - but the compiler should alert you to any instance where you are using an out-of-scope variable.