0

I am writing a program that has a bigger struct and a smaller struct, the smaller one holding names of friends of the person in index 0 of a 2D array in Friends. I wrote the whole thing from scratch a few times and it keeps giving me either seg fault or Thread 1: EXC_BAD_ACCESS (code=1, address=0x0).

Here are my structs:


3
  • Please post all related code. what does expandBig do? What does expandFriends do? Please post an minimal reproducible example. Please post all code in one big code block, so that it is easy to copy it. Commented Jan 24, 2020 at 2:00
  • With add2people(People * people, char * val), who are the 2 people added? Commented Jan 24, 2020 at 9:56
  • There is no "2d array in Friends". Commented Jan 24, 2020 at 10:01

1 Answer 1

2

expandBig() and expandFriends() do not assign values to the new data.

Looks like at least a problem is name assignment.

friends->name[friends->size] is not assigned a value after expandFriends(friends), so strcpy() fails.

void addFriend(Friends * friends, char * val) {
  if(friends->size == friends->cap)
      expandFriends(friends);
  strcpy(friends->name[friends->size], val);
  ....

Consider using strdup()

  // strcpy(friends->name[friends->size], val);
  friends->name[friends->size] = strdup(val);

... and in InitializeFriends()

  friend->name[i] = NULL;

Code such as below is tedious to review.
Was the size right? IDK, now have to trudge up to friend, find its type. OK that is Friends. Now look for Friends definition and see member char ** name. OK, now with char ** de-referenced we get char *. That matches codes sizeof(char*), so sizeof(char*) OK.

friend->name = realloc(friend->name, sizeof(char*) * friend->cap);

Save time. Code to the size of the de-referenced pointer, not the type. This is easier to code right, review and maintain.
Was the size right?
Yep, by construction, sizeof *(friend->name) is the right size.

// friend->name = realloc(friend->name, sizeof(char*) * friend->cap);
friend->name = realloc(friend->name, sizeof *(friend->name) * friend->cap);

// People * ret = (People*)calloc(DEFAULT_CAP, sizeof(People));
People * ret = calloc(DEFAULT_CAP, sizeof *ret);

Unclear why code sometimes casts the return from a *alloc() call and sometimes did not. The cast is not needed.

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

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.