簡體   English   中英

為什么會出現細分錯誤錯誤

[英]Why is the segmentation Fault error occuring

我收到錯誤細分錯誤(核心已轉儲)

我已經將其縮小到功能threadx中的這些行

    while (colatz_nums[j] != 1)
         {j++;
            if ((m % 2)==0)
            { colatz_nums[j]  = m/2;}

            else
            {colatz_nums[j]  = 3 * m +1;}
        } 

如果我刪除這些行,我不會收到錯誤消息。 我添加了一個while循環測試,它可以正常工作,因此這些行中一定有此內容。 請指出錯誤

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>  // pid_t
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <sys/fcntl.h>
#include <sys/stat.h>

#include <pthread.h>

#define N 2

void *thread (void *vargp);
void *threadx(void *vargp);

char **ptr;

int fib_nums[25] ;
int colatz_nums[25];
int last_collatz = 0;

int main()
{

    int i;
    pthread_t tid[2];
    char *msgs[N] = {
        "Hello from foo",
        "Hello from bar"
    };

    printf("Parent thread started with PID= %d and parent PID %d\n", getpid(), getppid());

    ptr = msgs;

    pthread_create(&tid[0], NULL, thread, (void *)1);
    printf(" 1st thread started with PID= %d and parent PID %d\n", getpid(), getppid());


    pthread_create(&tid[1], NULL, threadx, (void *)2 );
    printf("2nd  thread started with PID= %d and parent PID %d\n", getpid(),      getppid());

    pthread_join(tid[1], NULL);
    pthread_join(tid[0], NULL);
}

void *thread(void *vargp)
{
    int myid = (int)vargp;
    static int cnt = 0;
    printf(" thread ");

    int i=cnt;
    for (;i <10 ;i=i+1)
    {
        printf("[%d]  %d\n",myid, i);
        sleep(cnt);
    }

    return NULL;
}

void *threadx(void *vargp )
{
    int myid = (int)vargp;
    static int cnt = 0;
    printf(" threadx \n" );
    int j = 0;
    int m = 8;
    colatz_nums[0] = 8;

    while (colatz_nums[j] != 1)
    {
        j++;
        if ((m % 2)==0)
        {
            colatz_nums[j]  = m/2;
        }

        else
        {
            colatz_nums[j]  = 3 * m +1;
        }
    }
    last_collatz = j;

    for (j=0; j <= last_collatz; j++)
        printf ( " j %d",colatz_nums[j]);

    printf ( "\n");
    return NULL;
}

您永遠不會檢查colatz_nums 您正在使用j訪問它,並且將其遞增而不將其限制為24。

你先執行

colatz_nums[0] = 8

它將數組的第一個值設置為8。然后將它與不是的1進行比較,然后循環直到在數組中找到1。

循環中的問題是,您首先增加j然后將位於索引j的值(這是您將在下一輪循環中對下一個值進行測試的下一個值)設置為永遠不會為1(4或25,但在您的示例中始終為4)。

然后,您將永遠循環,直到發生崩潰(超出限制的訪問權限)。

m 從未改變,因此colatz_nums[j] 一直設置為4 (因為m為8,是偶數),一直到您從數組末尾跑出的那一點為止。

您可以通過將以下行作為while循環的最后一行來解決此問題:

m = colatz_nums[j];

或將其重寫為更安全的變體,從而避免未定義的行為:

while (colatz_nums[j] != 1) {
    j++;
    if ((m % 2)==0)
        m  = m / 2;
    else
        m  = 3 * m + 1;

    if (j == sizeof(colatz_nums) / sizeof(colatz_nums[0])) {
        fprintf (stderr, "Buffer overflow\n");
        exit (1);  // or some other method of stopping
    }
    colatz_nums[j]  = m;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM