ошибка в памяти, которая уже есть - PullRequest
1 голос
/ 11 апреля 2019

Так что я только начал использовать valgrind и с трудом выяснил, что же это за ошибки и что означает число.например, я получаю ошибку сегмента в этой строке.(Я знаю это не потому, что valgrind показал мне, а я просто помещаю каждую строку обратно в my и проверяю, пока не произойдет сбой при запуске моей программы *, которая в function2 в моем коде)

 int what = t->count; 

Ее попыткавытащить память из моего числа int в моем списке структуры заказов, и я знаю, что я сделал это заранее.Я не знаю, почему я не могу вытащить это.некоторые могут сказать мне, что пытается сказать мне valgrind?

Я пытался убедиться, что программа не обнаруживает ошибки где-либо еще.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "orderList_ccarver4_211.c"

void selectChoice();
void function1();
void function2();

typedef struct _robotOrder
{
    unsigned char robotNum;
    orderList *data;
    char *deliverTo;
    char *restaurant;
    struct _robotOrder *next;
} robotOrder;

robotOrder *deliveryList; /* the head of linked list of robotOrders */
robotOrder *addfront(robotOrder *head, robotOrder *value);

int main(void){
    deliveryList = (robotOrder*)dmalloc(sizeof(robotOrder)); /* the head of linked list of robotOrders */

    selectChoice(); /* choice menu function*/

    return 0;
}

void selectChoice()
{
    int T = 1;
    char line[4];
    char c;
    do{
        printf(" New delivery order? (y/n) "); /* get users choice*/
        fgets(line, sizeof(line), stdin);
        c = line[0];

        printf("yo this is it = %c\n", c);

        switch (c)
        {
        case 'y':
            function1();
            break;
        case 'n':
            printf("here");
            function2();
            break;
        default:
            printf("Invalid Input. Try again\n");

        }
    } while(T > 0);
}

robotOrder* addfront(robotOrder *head, robotOrder *value) /* function that adds to the list in the front */
{
    robotOrder *p,*q;
    p = (robotOrder*)dmalloc(sizeof(robotOrder));
    q = (robotOrder*)dmalloc(sizeof(robotOrder));
    p = head;
    q = value;
    q->next= p;
    return (q);
}

void function1(){

    robotOrder *or = (robotOrder*)dmalloc(sizeof(robotOrder)); /* makes a new robot order */

    char string[5];
    int num;
    printf("Task Robot Number: "); /* gets the num of the robot*/
    fgets(string, 4, stdin);
    num = atoi(string);
    or->robotNum = num;

    char *line;
    line=(char*)malloc(30*sizeof(char));
    printf("Delivery Address for new delivery order: "); /* gets the address*/
    fgets(line,sizeof(line), stdin);
    sscanf(line,"%s",&line);
    or->deliverTo = line;


    char *lines;
    lines=(char*)malloc(30*sizeof(char));
    printf("Restaurant from which to pick up food: "); /* gets the name of the restaurant*/
    fgets(lines,sizeof(lines), stdin);
    sscanf(lines,"%s",&lines);
    or->restaurant = lines;

    int loop = 0;
    char l[20];
    createItem();
    orderList *p = (orderList*)dmalloc(sizeof(orderList));
    int s = 0;
    while(loop == 0){
        printf("food item: "); /* keeps asking for food items*/
        fgets(l,sizeof(l), stdin);
        sscanf(l,"%s",&l);
        if(l[0] == '\n'){
            loop = 1; /* ends the loop if there wasnt any input */
        }
        if(l[0] != '\n'){
            s = s + insert(l, p); /* takes in the orderlist that in the robotorder */
        }
    }
    p->count = s;
    or->data = p; /* sets the orderlist to the robotOrder */

    deliveryList = addfront(deliveryList, or); /* add the node to the end of the list */

}

void function2(){
    printf("hello ?");
    robotOrder *p = (robotOrder*)dmalloc(sizeof(robotOrder));
    p = deliveryList;
    orderList *t = (orderList*)dmalloc(sizeof(orderList));
    while(p != NULL){ /* prints out info of the deliveries */
        t = p->data;
        int what = t->count;
        printf("Robot %d: Delivery order from %s has %d food item(s)", p->robotNum, p->restaurant,what);
        p = p->next;

        printf("\n");
    }
    printf("goodbye");
    exit(0); /* exit program */
}

orderList c file

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "orderList_ccarver4_211.h"

orderList *createItem(){
    orderList *lis = (orderList*)dmalloc(sizeof(orderList));
    lis->count = 0;
    lis->head = NULL;
}

int insert(char *str, orderList *s){
    foodNode *h;
    h = (foodNode*)dmalloc(sizeof(foodNode));
    h = s->head;
    int len = s->count;


    foodNode *q;
    q = (foodNode*)dmalloc(sizeof(foodNode)); /* makes new node */
    q->data = str;

    if(s->head == NULL){
        h=q;
        s->head = q;
        len++;
        s->count = len;
        return 1;
    }
    char *str2 = h->data; /* grabs the data*/
    int com = strcmpi(str, str2);
    while(h != NULL) {
        if(h->next == NULL){
            h->next = q;
            len++;
            s->count = len;
            return 1;
        }
        h = h->next;
    }
    return 0;
}

void printItems(orderList *s){
    foodNode *p;
    p = (foodNode*)dmalloc(sizeof(foodNode));
    p = s->head;
    while(p != NULL){
        printf("%s", p->data);
        p = p->next;
    }
}

/* compares strings for alphabetical ordering */
int strcmpi(char *s, char *t)
{
    while (*s && tolower(*s) == tolower(*t))
    {
        s++;
        t++;
    }
    return tolower(*s) - tolower(*t);
}

/* allocates memory with a check for successful allocation */
void *dmalloc(size_t size)
{
    void *p = malloc(size);
    if (!p)
    {
        printf("memory allocation failed\n");
        exit(1);
    }
    return p;
} 

файл списка заказов h

#ifndef ORDERLIST_CCARVER4_211_H
#define ORDERLIST_CCARVER4_211_H

typedef struct _foodNode
{
   char *data;  // Food Item Names
   struct _foodNode *next;
} foodNode;

typedef struct _orderList
{
   foodNode *head;  // Pointer to first food item for the order (alphabetical)
   int count;   // Number of food items in the order
} orderList;

orderList *createItem();
int insert(char *str, orderList *s);
void printItems(orderList *s);
int strcmpi(char *s, char *t);
void *dmalloc(size_t size);

#endif

Это то, что дал мне Вальгринд, что означает чтение размера 1 и где я должен искать?

== 1612 == Invalidчтение размера 1
== 1612 == в 0x4E81EF9: vfprintf (vfprintf.c: 1635)
== 1612 == по 0x4E88328: printf (printf.c: 34)
== 1612 ==по 0x400D5E: function2 (Project3_ccarver4_211.c: 127)
== 1612 == по 0x400A9C: selectChoice (Project3_ccarver4_211.c: 50)
== 1612 == по 0x400A10: основной (Project3_ccarver4_211.c)1023 * == 1612 == Адрес 0x61646e6170 не является стековым, malloc или (недавно) свободным
== 1612 ==
== 1612 ==
== 1612 == Процессзавершение с действием по умолчанию для сигнала 11 (SIGSEGV)
== 1612 == Доступ не в сопоставленной области по адресу 0x61646E6170
== 1612 == по адресу 0x4E81EF9: vfprintf (vfprintf.c: 1635)
==1612 == по 0x4E88328: printf (printf.c: 34)
== 1612 == по 0x400D5E: function2 (Project3_ccarver4_211.c: 127)
== 1612 == по 0x400A9C: выберите выбор (Project3_ccarver4_211.c:50)
== 1612 == по 0x400A10: main (Project3_ccarver4_211.c: 26)
== 1612 == Если вы считаете, что это произошло в результате стека
== 1612 == переполнение вОсновной поток вашей программы (маловероятно, но возможно
== 1612 ==), вы можете попытаться увеличить размер стека основного потока
== 1612 ==, используя флаг --main-stacksize =.
== 1612 == Размер стека основного потока, использованный в этом прогоне, был 8388608.
herehello? Робот 27: заказ на доставку от == 1612 ==

...