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
numbytesand is it 10 or larger?idis being overwritten past the 10 bytes you allocated for it. You should try usingstrncpyto bound the copy to max 10. However, you'll also have to ensureidhas a terminator at the last byte as well (strncpy doesn't guarantee a terminator).