Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't assign values to variable and pointer [duplicate]

Tags:

c

pointers

I'm very new to C, but have no idea why this program breaks. The program compiles and runs if I remove the lines that have to do with i, but if I assign i, I can no longer assign anything to *ptr without the program breaking.

int main(void)
{
    int i;
    int *ptr;

    i = 2;
    *ptr = 5;
    printf("%d",*ptr);
}
like image 404
Rob Volgman Avatar asked Jul 02 '12 16:07

Rob Volgman


People also ask

Can we assign value to pointer variable in C?

The key is you cannot use a pointer until you know it is assigned to an address that you yourself have managed, either by pointing it at another variable you created or to the result of a malloc call.

Can you use pointers in Python?

No, we don't have any kind of Pointer in Python language. The objects are passed to function by reference. The mechanism used in Python is exactly like passing pointers by the value in C.

Are dictionaries pointers in Python?

You can only reference objects in Python. Lists, tuples, dictionaries, and all other data structures contain pointers.


1 Answers

You leave the pointer with uninitialized value. So when you dereference it (*ptr), you access arbitrary place in memory, resulting in a segmentation fault.

Point ptr at something by assigning to ptr itself (not *ptr) an address of a variable (like &i) or some freshly allocated memory (like malloc(sizeof(int))).

like image 183
Kos Avatar answered Oct 12 '22 23:10

Kos