0

I have a query regarding the dynamic memory allocation of a integer pointer.

    int main()
    {
        int *a;
        *a = 5;
        printf("value = %d\n", *a);
        return 0;
    }

As per my understanding, the above piece of code should return segmentation fault, which happening in my PC (Ubuntu 32bit).

But the same piece of code, when executed on my MacOS and a Fedora Linux system gives output as "value = 5". Any idea, why this code is working on these two systems, even when I have not allocated memory for integer pointer?

3
  • 3
    "Undefined behavior" is not the same as "segmentation fault". Commented Jan 30, 2019 at 17:51
  • 1
    Well, since there is no dynamic or whatever allocation in the code, it is not clear why this question is about "dynamic memory allocation". Commented Jan 30, 2019 at 17:52
  • 1
    "code should return segmentation fault," is like saying if you cheat on a test you should get caught. Maybe you will, maybe you will not. If you need a language to tell you when code cheated, consider other languages. C simply is not required to do that. Commented Jan 30, 2019 at 17:53

3 Answers 3

4

A segmentation fault occurs when the system detects that you use a wrong memory address. Apparently this does not happen in your case.

The uninitialized pointer may point to some memory that you are allowed to read and write. Writing to this address may change unrelated data or may change the machine code of your program and may lead to a crash or strange behavior later. The behavior is undefined and may change when you modify unrelated parts of your program.

To check for this type of problem you could use tools like valgrind.

Sign up to request clarification or add additional context in comments.

Comments

3

I think anytime you have to deal with memory in the way your code snippet is doing, you enter in the territory of undefined behaviour. Your pointer might have been randomly initialized to a valid memory location, and therefore the assighment will work. If you want to test a 100% chance failure, you should initialize a to NULL.

Comments

1

When you dereference an uninitialized pointer, you invoke undefined behavior. This means you can't predict how the program will react. It might crash, it might output strange results, or it may appear to work properly.

This is why it "works" on one system but crashes on another. Just because you do something that might cause a crash doesn't mean it will.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.