2012-05-26 37 views
2

当调用函数(log_msg_send)时,我在下面的代码的运行时获得了SIGSEGV - Segmentation Fault。我读到它是关于内存违规,但我找不到原因。我希望有任何建议/帮助。C中的SIGSEGV(分段错误)

#define MAXSTRINGLENGTH 128 
#define BUFSIZE 512 

void log_msg_send(char *message, char *next_hop); 

struct routing { 
     int hop_distance; 
     char sender_ID[16]; 
}; 

struct routing user_list[40] = { [0]={0,0,0,0}}; 


int main(int argc,char *argv[]){ 
    strcpy(user_list[0].sender_ID,"192.168.001.102"); 
    char message[1000]; 
    strcpy(message,"123456123456"); 
    log_msg_send(message, user_list[0].sender_ID); 

    return 0; 
} 

void log_msg_send(char *message, char *next_hop){ 
    char *SRV_IP; 
    strcpy(SRV_IP, next_hop); 

    if (sizeof(SRV_IP) == 16){ 
     struct sockaddr_in si_other; 
     int s, i, slen=sizeof(si_other); 
     char buf[60] ; 
     strcpy(buf, message); 

     if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1){ 
      fprintf(stderr, "socket() failed \n"); 
      exit(1); 
     } 

     memset((char *) &si_other, 0, sizeof(si_other)); 
     si_other.sin_family = AF_INET; 
     si_other.sin_port = htons(33333); 
     if (inet_aton(SRV_IP, &si_other.sin_addr) == 0) { 
      fprintf(stderr, "inet_aton() failed \n"); 
      exit(1); 
     } 

      if (sendto(s, buf, BUFSIZE, 0,(struct sockaddr *) &si_other, slen)==-1){ 
      fprintf(stderr, "sendto() failed \n"); 
      exit(1); 
     } 

     close(s); 
    } 
} 

PS。对于有SIGSEGV问题的人。对于SIGSEV问题,大多数common reasons: - 尝试执行无法正确编译的程序。请注意,大多数编译器在编译时错误时不会输出二进制文件。 - 缓冲区溢出。 - 使用未初始化的指针。 - 取消引用NULL指针。 - 尝试访问程序不拥有的内存。 - 尝试更改程序不拥有的内存(存储违规)。 - 超过允许堆栈大小(可能是由于失控递归或无限循环)

+1

你可以使用“valgrind”来自己轻松解决这类问题。只需安装,然后像平常一样运行你的程序,但是把valgrind放在命令行上的程序名之前。它会检测到错误并打印出一条消息。 –

+0

投票关闭,为什么不是这段代码工作。 –

回答

4

你不分配内存SRV_IP

char *SRV_IP; 
strcpy(SRV_IP, next_hop); 

所以strcpy试图访问无效的内存。

char *SRV_IP = malloc(strlen(next_hop)+1); 
if (!SRV_IP) exit(1); 
strcpy(SRV_IP, next_hop); 

然后你检查

if (sizeof(SRV_IP) == 16){ 

SRV_IPchar*,所以它的大小是任意大小char指针有,通常是8或4个字节。你可能是指长度,所以必须使用strlen

+0

非常感谢您的明确解释 – johan

+1

也许您即将添加此内容,但我猜'sizeof'应该是'strlen'。 –

+0

@andrew cooke,谢谢 – johan