Reputation: 1
I am working with pointers and arrays where I have to specify where does the array starts in memory or what memory address the pointer should hold. The pointer or array takes the address; however, I cannot deference or assign a value.
I tried to run following code but it gives me Segmentation Fault. What am I doing wrong here? Please help!
int *a = (int *)0x100;
cout << a << endl; //prints out 0x100
*(a) = 10; <------ seg fault on this line
following the code for array,
int *b = new b[10];
b = (int *)0x0;
cout << b << endl; //prints out 0x0
b[0] = 10; <---- seg fault on this line
Upvotes: 0
Views: 627
Reputation: 238311
What am I doing wrong here?
You are dereferencing a pointer that does not point to an object. That has undefined behaviour, but if you are in luck, the OS may detect the mistake and raise a seg fault.
Solution: First allocate memory for an object. How you should allocate, depends on how you intend to use the object. A simple way to allocate an object is to use an automatic variable:
int main() {
int object;
int* pointer = &object; // now you can assign the pointer to the specific memory address of the existing object
*pointer = 10; // dereferencing is OK
}
flag
wouldn't pointer takes address of object which is not specified?
The pointer would take the address of the specified object. The compiler specifies what the address will be.
How can I make pointer point to address 0x100 ...
Using a cast. Your program already does that.
... and use that memory for my purpose?
Using arbitrary memory not possible in standard C++. You will need to resort to platform specific ways to deal with your problem.
Upvotes: 2
Reputation: 133
allocate memory first for int a, you are segfaulting because of that.
int *a = new int;
*a = 10;
delete a;
for you second case you are also dereferencing a null pointer. you dont need to set b to address zero. by doing so i believe you lose your array.
Upvotes: 0