C中的动态数组 - 异常抛出

时间:2015-12-30 13:53:35

标签: c exception dynamic-arrays

我已经开始在C中使用动态数组,我得到一个异常抛出的运行时错误:

  

在赋值3.exe中的0x00007FF7ECB21A87抛出异常:0xC0000005:访问冲突写入位置0xFFFFFFFFE7CBC420。

这发生在insertArray()函数中,当我尝试将char元素存储在struct Array中找到的数组变量中时(见下文):

代码:

#include <stdio.h>
#include "header3.h"

typedef struct {
    char *array;
    size_t used;
    size_t size;
} Array;

typedef struct {
    int *array;
    size_t used;
    size_t size;
} intArray;

void initArray(int option, Array *a, intArray *b, size_t initialSize) {
    if (option == 1) {
        a->array = (int *)malloc(initialSize * sizeof(char));
        a->used = 0;
        a->size = initialSize;
    }
    else {
        b->array = (int *)malloc(initialSize * sizeof(int));
        b->used = 0;
        b->size = initialSize;
    }
}

void freeArray(int option, Array *a, intArray *b) {
    if (option == 1) {
        free(a->array);
        a->array = NULL;
        a->used = a->size = 0;
    }
    else {
        free(b->array);
        b->array = NULL;
        b->used = b->size = 0;
    }
}

void insertArray(int option, Array *a, intArray *b, char element, int element2) {
    if (option == 1) {
        if (a->used == a->size) {
            a->size *= 2;
            a->array = (char *)realloc(a->array, a->size * sizeof(char));
        }
        a->array[a->used++] = element; //ERROR HERE
    }
    else {
        if (b->used == b->size) {
            b->size *= 2;
            b->array = (int *)realloc(b->array, b->size * sizeof(int));
        }
        b->array[b->used++] = element2;
    }
}


int main() {
    Array eq, postFx;
    initArray(1, &eq, 0, 2);  // initially 2 elements
    initArray(1, &postFx, 0, 2);
    int i;
    char C;
    printf("Enter character string\n");
    while ((C = getchar()) != EOF)
        insertArray(1, &eq, 0, C, 0);  // automatically resizes as necessary
    //int n = expEvaluate(eq, (eq.used)-1, postFx); //call expEvaluate to process eq
    //printf("\nAnswer: %d", n);
    int chk = getchar(); //readkey (twice)
    freeArray(1, &eq, 0);
    chk = getchar();

    return 0;
}

我似乎无法理解这一点,我可能会遗漏一些显而易见的事情,或者问题比那更大......无论哪种方式,我都很感激!

1 个答案:

答案 0 :(得分:0)

  1. 在initArray中:[int allocate:(int *)...]

    a->array = (int *)malloc(initialSize * sizeof(char));
    

    在insertArray中:[char allocate:(char *)...]

    a->array = (char *)realloc(a->array, a->size * sizeof(char));
    
  2. 它会导致问题。

    1. 使用gdb:GNU Debugger