Ошибка буфера "чтение / запись вне границ" с использованием блокировок мьютекса - PullRequest
0 голосов
/ 15 марта 2019

Я работаю над использованием нескольких потоков в c и столкнулся с этой ошибкой при использовании segfault.stensal.com ... Я не могу понять, почему у меня есть чтение и запись связанных ошибок.Любое направление здесь было бы замечательно.Я знаю, что блокировки обычно используются, когда у вас есть 2 или более потоков, изменяющих одни и те же или похожие данные, поэтому я буду изменять свой буфер так, чтобы он действовал больше как стек, но пока я хотел убедиться, что мой код работаетс простым массивом.

=========== Начало # 0 сообщения времени выполнения stensal ===========

Ошибка времени выполнения: [out-of-bounds write]
Продолжение выполнения может привести к неопределенному поведению, прервать!

-
- Writing 4 bytes to 0x818a6d4 will corrupt the adjacent data.
- 
- The memory-space-to-be-written (start:0x8189730, size:4000 bytes) is bound to 'buffer' at
-     file:/prog.c::14, 0
- 
-  0x8189730               0x818a6cf
-  +------------------------------+
-  |the memory-space-to-be-written|......
-  +------------------------------+
-                                     ^~~~~~~~~~
-           the write starts at 0x818a6d4 that is 4 bytes after the memory end.
- 
- Stack trace (most recent call first) of the write.
- [1]  file:/prog.c::86, 18
- [2]  file:/musl-1.1.10/src/thread/pthread_create.c::168, 17
- [3]  file:/musl-1.1.10/src/internal/c_abi_func.c::51, 8
-
```(56,208)

============ End of #0 stensal runtime message ============

=========== Start of #1 stensal runtime message ===========

  Runtime error: **[out-of-bounds read]**  
  Continuing execution can cause undefined behavior, abort!

```stensal-diagnostic-info
-



My code is as follows:



#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define BUFFER_SIZE (50)

typedef struct  {

        int pc1, pc2;

} Prodcons;

Prodcons buffer[500];

pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;

int pc1C;
int pc2C;


void *Producer();
void *Consumer();


int main(int argc, char *argv[])
{
        pthread_t tid1;
        pthread_t tid2;
        pthread_attr_t attr;
        void *my_Ptr;

        if (argc == 1)
        {
                printf("usage: ./assn3 <number to factor>\n");
                return -1;
        }

        if (argc < 0)
        {
                fprintf(stderr, "%d must be >= 0\n", atoi(argv[1]));
                return -1;
        }


        for(int i = 0; i < argc - 1 ; i++)
        {
            pthread_mutex_lock(&lock1);
            buffer[i].pc1 = (atoi(argv[i + 1]));
            pc1C++;
            pthread_mutex_unlock(&lock1);

        }

        pthread_attr_init(&attr);

        pthread_create(&tid1, &attr, Producer, NULL);
        pthread_create(&tid2, &attr, Consumer, NULL);

        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);
}

void *Producer()
{

        for (int j = 0; j < pc1C; j++)
        {

            pthread_mutex_lock(&lock2);

            int myNum = buffer[j].pc1;




            if (myNum == 1)
            {
                    buffer[pc2C].pc2 = 1;
                    pc2C++;
            }

            while (myNum % 2 == 0)
            {
                   buffer[pc2C].pc2 = 2;
                   myNum = myNum/2;
                   pc2C++;
            }

            for (int i = 3; i <= sqrt(myNum); i += 2)
            {
                    while (myNum % i == 0)
                   {
                            buffer[pc2C].pc2 = i;
                            myNum = myNum/i;
                            pc2C++;
                   }
            }


            if (myNum > 2)
            {
                   buffer[pc2C].pc2 = myNum;
                   pc2C++;
            }


            buffer[pc2C].pc2 = -1;

            pthread_mutex_unlock(&lock2);

        }

        pthread_exit(NULL);

}



void *Consumer()
{
    for (int i = 0; i < pc1C; i++)
        {

                printf("%d: ", buffer[i].pc1);

                int j = 0;

                while (buffer[j].pc2 != -1 )
                {
                   //   printf("%d ",buffer[j].pc2);
                    j++;
                }

                printf("\n");
        }

    pthread_exit(NULL);

}
...