0

Im having trouble trying to print out and store a char array. The char array "id" is stored in a struct which is then stored in an array of that struct. when i try to print the id i get a seg fault. any help would be great. this is the struct

{
  const int NUM_MAX_FILES = 50;
  const int FILE_NAME_MAX_LENGTH = 256;
  typedef struct {
    char id[10]; //id
    char* addr; // The IP of the peer
    int file_count; // number of files
    char files[NUM_MAX_FILES][FILE_NAME_MAX_LENGTH]; // The files the peer broadcasts
} peer_struct;

Which is then stored into an array

peer_struct more_peers[50];

I have a nested loop that compares each peer and its files, to search for a matching file. Which works great, but when i try to get the id of the peer with the match i get a seg fault. here is the code for if its a match.

if(strcmp(buf,more_peers[i].files[y]) == 0){
    printf("Found a match: ");
    printf("%s\n",more_peers[i].id); <-- this is where I get a seg fault.
    strcpy(val,more_peers[i].id);//store the value
}

and here is the code adding a new peer with a id

 recv(new_tcp_s, buf, MAXDATASIZE, 0);
 buf[numbytes] = '\0';
 strcpy(tmp_peer.id,buf);
 printf("REG publish: peer id %s\n", tmp_peer.id ); <-- no seg fault here it 
 more_peers[ap_count] = tmp_peer;                   also prints the correct id
6
  • 1
    What is the value in numbytes and is it 10 or larger? Commented Nov 29, 2020 at 4:29
  • @BillLynch Yep its set to 100 Commented Nov 29, 2020 at 4:34
  • The most likely thing is that id is being overwritten past the 10 bytes you allocated for it. You should try using strncpy to bound the copy to max 10. However, you'll also have to ensure id has a terminator at the last byte as well (strncpy doesn't guarantee a terminator). Commented Nov 29, 2020 at 4:40
  • 1
    Better still, run this in a debugger, let it puke, and start scoping variables in your stack frames. I have little doubt you've breached fixed addressable space somewhere. Commented Nov 29, 2020 at 4:41
  • @DavidC.Rankin they get initialized and deleted as peers connected and disconnect. Commented Nov 29, 2020 at 4:41

1 Answer 1

2

In the comments you write that numbytes is 100. This means that you are writing past the end of the id array, which is only 10 bytes long.

Good practice would involve replacing the strcpy with a function that takes the size of the destination array as an argument. For example:

snprintf(tmp_peer.id, 10, "%s", buf);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.