gpt4 book ai didi

将数据复制到 C 中结构内部的字符串会导致段错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:13:38 24 4
gpt4 key购买 nike

我正在尝试将一个字符串 (myipaddr) 复制到另一个在结构内声明的字符串(中间)。我不能采用任何其他方式,因为我必须在另一个更大的代码中使用它。

如果我在 char *my_ip 函数中声明相同的字符串(中间),我在 memcpy 的行上遇到段错误,它工作正常。

主.c

 #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <sys/ioctl.h>
#include <net/if.h>
#include "private.h"

char *my_ip(char *myniccard, char *myipaddr) {

address_t *accessor = NULL;

int fd;
struct ifreq ifr;

myipaddr[0]=0;

fd = socket(AF_INET, SOCK_DGRAM, 0);

/* I want to get an IPv4 IP address */
ifr.ifr_addr.sa_family = AF_INET;

/* I want IP address attached to "eth0" */
//strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
strncpy(ifr.ifr_name, myniccard, IFNAMSIZ-1);

ioctl(fd, SIOCGIFADDR, &ifr);

close(fd);


/* display result */
sprintf(myipaddr,"%s"
, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

memcpy(accessor->middle, myipaddr, 16 * sizeof (char)); // here is segmentation fault.
printf("Buffer :%s\n",accessor->middle);

return (myipaddr);
} // my_ip



int main (){

char addr[22];
char *card = "wl1";

char *ip = (char *)malloc(sizeof (char));
ip = my_ip(card, addr);
free (ip);

return 0;
}

私有(private).h

#ifndef FILE_PRIVATE_HEADER
#define FILE_PRIVATE_HEADER

#include <sys/socket.h> // inet_aton
#include <netinet/in.h> // inet_aton
#include <arpa/inet.h> // inet_aton
#include "queue.h"
#include "bstrlib.h"

#define PGW_NUM_UE_POOL_MAX 16

typedef struct data {


char middle[PGW_NUM_UE_POOL_MAX];


}address_t;

#endif

最佳答案

函数my_ip 返回指向addr 第一个字符的指针。该指针不是您可以释放的东西。

让我们看这三行:

 char *ip = (char *)malloc(sizeof (char));
ip = my_ip(card, addr);
free (ip);

然后将它们一一呈现:

  1. char *ip = (char *)malloc(sizeof (char));

    此行定义变量 ip 并将其初始化为指向 malloc 调用返回的单字节

  2. ip = my_ip(card, addr);

    重新分配 指针,因此它不再指向由malloc 返回的内存。相反,它现在将指向 addr 的第一个字符(因为这是 my_ip 返回的内容)。

  3. 免费 (ip);

    现在您实际上尝试执行无效的 free(&addr[0])

简单的解决方案是既不调用 malloc 也不调用 free

关于将数据复制到 C 中结构内部的字符串会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51105539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com