简体   繁体   English

除内存分配外的分段错误

[英]Segmentation Fault besides memory allocation

I can't seem to figure out why my assignment to an char * [] is giving me a segmentation fault when I try and assign a value to [0]. 我似乎无法弄清楚为什么在尝试为[0]赋值时给char * []的赋值给我一个分段错误。

So what I mean is, I created a 所以我的意思是,我创建了一个

char * temp[255]

which should allocated space in the heap for the temp. 这应该为临时堆分配空间。 Thus when I do 因此,当我这样做

while(buffer)
{
    for(num = 0; num < i; num++)
    {
        if(strcmp(temp[i], buffer) == 0)
        {
            break;
        }
    }

    /* send menu choice to server indicating client wants list of all files on server */
    if (sendto(sock, menuOption, sizeof(menuOption), 0, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) < 0)
    {
        printf("sendto() sent a different number of bytes than expected");
    }

    /* receive a response from the server */
    fromSize = sizeof(fromAddr);
    if ((recvDataLen = recvfrom(sock, buffer, sizeof(buffer), 0, (struct sockaddr *) &fromAddr, &fromSize)) < 0)
    {   
        printf("recvfrom() failed\n");
    }

    if(serverAddr.sin_addr.s_addr != fromAddr.sin_addr.s_addr)
    {
        fprintf(stderr,"Error: received a packet from unknown source.\n");
        exit(1);
    }

    /* null terminate the received data */
    buffer[recvDataLen] = '\0';
    strcpy(temp[i], buffer);
    i++;
    printf("%s\n", buffer);    /* Print the echoed arg */
}

I should not be getting a segmentation fault, because i is initialized to 0 (I have not shown the initialization here because i is set at the top of my file along with socket attributes). 我不应该遇到分段错误,因为我已初始化为0(因为我与套接字属性一起位于文件的顶部,所以未在此处显示初始化)。 So in the first iteration of the while loop, the for loop does nothing because num and i are both zero, thus it proceeds to send data to the server and retrieve data from the server. 因此,在while循环的第一次迭代中,for循环不执行任何操作,因为num和i均为零,因此它将继续向服务器发送数据并从服务器检索数据。 That data is put into buffer and should be then copied into temp. 该数据将放入缓冲区,然后应复制到临时文件中。 However it just gives me a segmentation fault and crashes. 但是,这只是给我一个分段错误而崩溃。 Any ideas why? 有什么想法吗?

Your char* temp[255]; 您的char* temp[255]; is not what you think. 不是你的想法。 It is an array of 255 pointers . 它是255个指针的数组。 Not strings. 不是字符串。 Your pointers are uninitialized so they point to completly random places, which causes your segmentation fault. 您的指针未初始化,因此它们指向完全随机的位置,这会导致分段错误。 To Avoid this you need to allocate memory for every pointer. 为了避免这种情况,您需要为每个指针分配内存。

char* temp[255] = {0}; // set all pointers to 0
//...
for(num = 0; num < i; num++)
{
   if(temp[i] != 0 && strcmp(temp[i], buffer) == 0) // if a pointer is 0 (uninitialized), do not access it
   {
      break;
   }
}
//...
temp[i] = malloc(size); // probably (strlen(buffer) + 1) (except you use something else for buffer)
if(temp[i] == NULL)
{
// something bad happend.
}
strcpy(temp[i], buffer);

You have declared an array of 255 pointers: 您已声明255个指针的数组:

char * temp[255];

So you can do the following with these: 因此,您可以使用以下方法执行以下操作:

char actual_data[5] = {0};
strcpy (actual_data, "Heya");
temp[0] = actual_data;     //temp[0] now points to "heya"

But you cannot do: 但是您不能做:

strcpy (temp[0], actual_data);

This is because temp[0] is a pointer and does not have any memory of its own other than 4/8 bytes (equal to an integer). 这是因为temp [0]是一个指针,除了4/8字节(等于整数)之外,没有任何自己的内存。 If you want to strcpy then you need to allocate memory. 如果要strcpy,则需要分配内存。 You can do something like: 您可以执行以下操作:

char actual_data[5] = {0};
strcpy (actual_data, "Heya");
char *temp[255];
for (i=0; i<255; i++) 
{
     temp[i] = (char *)malloc (sizeof(actual_data) * sizeof(char));
     strcpy (temp[i], actual_data);
} 

This is just an example where all the 255 pointers will point to actual_data (hence "heya"). 这只是一个示例,其中所有255个指针都将指向Actual_data(因此为“ heya”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM