2

I have this function:

static pair_t * // not visible outside this file
pair_new(const int key)
{

  pair_t *pair = malloc(sizeof(pair_t));

  if (pair == NULL) {
    // error allocating memory for pair; return error
    return NULL;
  } else {


            printf("key is %d\n",key);

      *(pair->key) = key;
      *(pair->count) = 1;
      pair->next = NULL;
      return pair;

  }
}

but the way I am trying to dereference the key element of the instance of pair is giving me a seg fault. I think it is because 'pair' is a pointer.

the pair structure is defined as follows:

typedef struct pair {
  int *key;                // search key for this item
  int *count;                  // pointer to data for this item
  struct pair *next;   // children
} pair_t;

Any suggestions on how to properly change the value of key would be much appreciated

1 Answer 1

2

No, there's no issue with pair, it's with key (and the count, too). The pointer is used uninitialized which invokes undefined behavior.

At the point where you;re trying to dereference key

 *(pair->key) = key;

there's no valid memory allocated to key, so the dereference invokes UB. You need to allocate memory to key before you can use it. same goes for the count, too.

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

2 Comments

thanks, i added : pair->key = malloc(sizeof(int)); pair->count = malloc(sizeof(int)); and it seems to work now
@dirtyb You're welcome. You can also consider accepting an answer that helped you.

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.