2

I'm pretty new to C coding, and pointers are something I'm having a lot of trouble with. I'm trying to write a program that takes in 2 pointers as parameters, adds the value of the first to the second, then returns the value of the first. What I've written is this:

int foo(int *g, int *h)
{ 
    int a;
    a = *g; 
    *h += a;
    return a; 
}

However, I am getting a segmentation fault error using an online compiler. I read that these are caused by rogue pointers, but I'm not sure where the error is. Can someone help?

EDIT: I'm calling this function this way:

    main()
{
   int* x;
   *x = 3;
   int* y;
   *y = 4;
   int z = foo(x, y);
   printf("%d", z);
}

I thought that was the way to declare a pointer, and that using (*) to dereference it was how to assign it a value. Am I incorrect?

2
  • Make sure everything is right before the call. Commented Mar 3, 2014 at 16:37
  • 3
    How are you calling this function? Show us a short full example Commented Mar 3, 2014 at 16:37

2 Answers 2

3

In main you have to allocate spaces for x and y before you can use it. If x and y are not allocated spaces, they point to arbitrary memory locations. If they are outside of your program segment, you will get a segmentation fault.

main()
{
   int* x=malloc(sizeof(int));
   *x = 3;
   int* y=malloc(sizeof(int));
   *y = 4;
   int z = fun(x, y);
   printf("%d", z);
}

Or like this:

main()
{
   int x=3,y=4;
   int z = fun(&x, &y);
   printf("%d", z);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I was worried that it was a problem with the foo code, but it turns out it was, in fact, how I was declaring the variables. Your second solution worked perfectly.
0

This will cause a segfault because you are dereferencing a pointer that has not been initialized.

 int *x;    // declares pointer X
 *x = 3;    // seg fault here because x contains garbage and points certainly to 
            // invalid memory

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.