动态大小的购物清单中的内存分配错误(我认为?)。

时间:2016-08-08 13:02:10

标签: c pointers memory malloc

我已经包含了下面的代码,如果有人愿意使用它来真正看到问题。我试图制作一个动态分配的购物清单,让我习惯于指针和内存分配。

条目存储在1D char数组中(由空指针分隔)。还创建了包含第一个字符和条目长度位置的数组,以便导航列表。

该代码适用于小条目,但当我使用大型条目列表(例如' adsjasdkasjdaksdj')时,我的代码认为长度(strlen(消息))类似于' 110040& #39 ;.对我而言,这看起来像是一个记忆错误,但我不是计算机科学家(更多的是业余编码员)。我尝试使用realloc()扩展分配的内存,但问题仍然存在。任何帮助将不胜感激!

我已将代码放在循环中以获取10个条目用于测试目的。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int listEntries = 0;

int main(int argc, const char * argv[]) {

    //Initial definition and allocation of memory.
    char *list;
    list = (char *)malloc(sizeof(char)); //allocates the requested memory and returns a pointer to it.

    int *entryLength; //Array to hold length of each entry.
    entryLength = (int *)malloc(sizeof(int)); //allocates the requested memory and returns a pointer to it.

    int *entryStart; //Array to hold start point of each entry.
    entryStart = (int *)malloc(sizeof(int)); //allocates the requested memory and returns a pointer to it.

    char *message; //Array to hold the user input.
    message = (char *)malloc(sizeof(char)); //allocates the requested memory and returns a pointer to it.

    int arraySize = 0; //Variable to hold the size of the array.

    char input[32]; //Char array to take user input (copied to 'message' later)

    for(int i=0;i<10;i++){
        //Obtain user entry.
        printf("Insert entry: \n");
        scanf("%s",input);

    //Transfer string pointer contents to usable char array of known size.
        message = (char *)realloc(message, strlen(input)*sizeof(char));

        int i=0;
        while(input[i] != '\0'){
            message[i] = input[i];
            i++;
        }
        message[i]='\0';

        //Add entry to list.
        listEntries++;

        //Find the current size of list.
        arraySize=0;
        for(i=0;i<listEntries;i++) {
            arraySize+=entryLength[i];
            printf("entryLength[%d] = %d\n",i,entryLength[i]);
        }

        //Reallocate memory to accomodate new data.
        list = (char *)realloc(list, (arraySize+1)*sizeof(char)+2);
        entryLength = (int *)realloc(entryLength,(listEntries*4)*sizeof(int)+2); //Over allocating
        entryStart = (int *)realloc(entryStart,(listEntries*4)*sizeof(int)+2); //For safety in dev.

        //Add new entry to data.
        entryLength[listEntries-1]=(int)strlen(message);
        printf("entryLength[%d] is: %d",listEntries-1,entryLength[listEntries-1]);

        entryStart[listEntries-1]=arraySize;
        //printf("Start point is: %d",entryStart[listEntries-1]);

        for(i = 0; i < strlen(message); i++){
            list[i+arraySize] = message[i];
        }

        //Print the new entry
        for(int i = 0; i < arraySize; i++){
            printf("%c",list[i]);
        }
        printf("\n");
    }

}

0 个答案:

没有答案