0

Why am I getting segmentation fault with this code?

#include<stdio.h>
typedef struct
{
    int                 val;
} DEVICE;

main()
{
DEVICE  *dev_ptr;
dev_ptr->val = 21;
printf(" %d   ",dev_ptr->val);
}

I know the correct way of assigning the values. For that we need to add these lines

DEVICE simple;
dev_ptr = &simple;
simple.val = 21;

but I want to know what is wrong with previous code ?

2 Answers 2

3

When you assign to val, the dev_ptr is uninitialized, you never set it to point at somewhere valid.

So you're (probably) writing to a "random" location in memory, which (absolutely) gives undefined behavior.

The fix should be something like:

DEVICE my_device;
DEVICE *dev_ptr = &my_device;
dev_ptr->val = 21;
printf("my_device.val=%d\n", my_device.val);

The above will print 21.

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

Comments

2

In your first code, dev_ptr is used uninitialized. Using uninitialized memory leads to undefined behaviour, with a possible side effect of a segmentation fault.

You need to allocate memory [what you're doing in second snippet] to the variable before using [dereferencing] it.

You've got the compile-time memory allocation and using that address for dev_ptr absolutely correct in your second code snippet. Now, see the below code for dynamic allocation.

Try something like

int main()    // use proper signature
{
DEVICE  *dev_ptr = malloc(sizeof(DEVICE));   // allocate memory

  if (dev_ptr)                                 //check for malloc success
  {
    dev_ptr->val = 21;
    printf(" %d   ",dev_ptr->val);
  }

free(dev_ptr);                                 //make valgrind happy, prevent memory leak
return 0;                                      // have a return statement
}

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.