从类成员函数访问字符串数组

时间:2015-08-14 18:00:49

标签: c++ class dynamic-arrays member-functions

我正在使用基本类并尝试访问成员函数中的成员字符串数组。我很困惑因为如果我只调用set_wordsprint_wordsdel_words函数,字符串数组会初始化并释放而没有任何内存错误(Dr. Memory):

class XWORD {
  public:
    int vdir;
    int len;
    int wid;
    int nWords;
    char ** arr;
    char ** words;     
    ...
};

void XWORD::set_words(int istart, int inWords, char* iwords[]) {
    int w = istart;
    int k = 0;
    this->nWords = inWords;

    this->words = new char* [this->nWords];
    for (w=istart; w<(istart+this->nWords); w++) {
        this->words[k] = new char [1+strlen(iwords[w])];
        this->words[k] = strcpy(this->words[k], iwords[w]);
        k++;
    }
}

void XWORD::del_words() {
    int w = 0;
    for (w=0; w<(this->nWords); w++) {
        delete[] this->words[w];
    }
    delete[] this->words;
}

void XWORD::print_words() {
    int w = 0;
    for (w=0; w<(this->nWords); w++) {
        printf("\n%s",this->words[w]);
    }
    printf("\n");
}

但是,当我调用以下函数时,我得到下面显示的Dr.内存错误(init_arrdel_arr单独也不会出错):

void XWORD::add_word_to_arr(int iw, int iy, int ix) {
    int k = 0;
    int y = iy;
    int x = ix;

    for (k=0; k<(int)strlen(this->words[iw]); k++) {
        this->arr[y][x] = this->words[iw][k];
        if (this->vdir) {
            y++;
        } else {
            x++;
        }
    }
}

int main(int argc, char * argv[]) {
    XWORD x;
    x.set_words(1, argc-1, argv);
    x.init_arr(10,10);

    x.add_word_to_arr(0, x.len/2, x.wid/2); // WITHOUT THIS, NO ERRORS
    x.print_words();

    x.del_words();
    x.del_arr();
}

博士。内存错误:

c:\MinGW\WORKSPACE\cpp\xword>make runmem
drmemory -brief -batch bin/test.exe
~~Dr.M~~ Dr. Memory version 1.8.0
~~Dr.M~~ Running "bin/test.exe"
~~Dr.M~~
~~Dr.M~~ Error #1: UNADDRESSABLE ACCESS beyond heap bounds: reading 4 byte(s)
~~Dr.M~~ # 0 XWORD::add_word_to_arr               [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:301]
~~Dr.M~~ # 1 main                                 [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:302]
~~Dr.M~~ Note: refers to 0 byte(s) beyond last valid byte in prior malloc
~~Dr.M~~
~~Dr.M~~ Error #2: UNADDRESSABLE ACCESS: reading 1 byte(s)
~~Dr.M~~ # 0 replace_strlen                       [d:\drmemory_package\drmemory\replace.c:375]
~~Dr.M~~ # 1 XWORD::add_word_to_arr               [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:301]
~~Dr.M~~ # 2 main                                 [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:302]
~~Dr.M~~
~~Dr.M~~ Error #3: LEAK 0 bytes
~~Dr.M~~ # 0 replace_operator_new_array               [d:\drmemory_package\common\alloc_replace.c:2638]
~~Dr.M~~ # 1 XWORD::set_words                         [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:301]
~~Dr.M~~ # 2 main                                     [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:302]
~~Dr.M~~
~~Dr.M~~ Error #4: LEAK 40 direct bytes + 110 indirect bytes
~~Dr.M~~ # 0 replace_operator_new_array               [d:\drmemory_package\common\alloc_replace.c:2638]
~~Dr.M~~ # 1 XWORD::init_arr                          [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:301]
~~Dr.M~~ # 2 main                                     [../mingwrt-4.0.3-1-mingw32-src/src/libcrt/crt/crt1.c:302]
~~Dr.M~~
~~Dr.M~~ ERRORS FOUND:
~~Dr.M~~       2 unique,     2 total unaddressable access(es)
~~Dr.M~~       0 unique,     0 total uninitialized access(es)
~~Dr.M~~       0 unique,     0 total invalid heap argument(s)
~~Dr.M~~       0 unique,     0 total GDI usage error(s)
~~Dr.M~~       0 unique,     0 total handle leak(s)
~~Dr.M~~       0 unique,     0 total warning(s)
~~Dr.M~~       2 unique,     2 total,    150 byte(s) of leak(s)
~~Dr.M~~       0 unique,     0 total,      0 byte(s) of possible leak(s)
~~Dr.M~~ Details: C:\Users\jesse\AppData\Roaming\Dr. Memory\DrMemory-test.exe.4512.000\results.txt
~~Dr.M~~ WARNING: application exited with abnormal code 0xc0000005
make: *** [runmem] Error 5

另外,当我在this->words[0]函数中打印add_word_to_arr的“%s”时,它是null。然而,它可以从print_words();打印出来。

exe调用是:

bin\test.exe a123 b123

init_arr()是:

void XWORD::init_arr(int ilen, int iwid) {
    int y = 0;
    int x = 0;
    this->len = ilen;
    this->wid = iwid;

    this->arr = new char* [this->len];
    for (y=0; y<(this->len); y++) {
        this->arr[y] = new char [1+this->wid];
        for (x=0; x<(this->wid); x++) {
            this->arr[y][x] = BLANK;
        }
        this->arr[y][x] = (char) NULL;
    }
}

2 个答案:

答案 0 :(得分:0)

Ok init_arr(10,10)初始化一个10个大小为11的char数组的数组(10个字符+ 1个终止空值)。

然后,调用add_word_to_arr(0, 5, 5),以便将第一个单词(命令行的第一个参数)复制到从位置5,5开始的数组中。因此,如果该字至少为7个字符且vdir == 0或6与vdir!= 0,则写入保留的数组。我可以使用params“foo”和“bar”成功运行,但不能使用“feefoobar”。

您应该计算最长单词的长度,并在调用int_arr

时使用它

无论如何,它看起来你测试vdir值而不在任何地方初始化它。这会导致未定义的行为,因为您无法知道将遵循哪个分支(水平或垂直),并且您真的应该以这种方式重写add_word_to_arr

void XWORD::add_word_to_arr(int iw, int iy, int ix) {
    int k = 0;
    int y = iy;
    int x = ix;

    for (k=0; k<(int)strlen(this->words[iw]); k++) {
        this->arr[y][x] = this->words[iw][k];
        if (this->vdir) {
            if (++y >= this.len) return; // refuse to write past allocated mem
        } else {
            if (++x > this.wid) return; // refuse to write past allocated mem
        }
    }
}

我在强制vdir值一次为0并且一次为1之后在调试器下执行它,它从未访问过去分配的内存。但我不得不想象一些代码,因为你没有给出Minimal Compilable Verifiable example

答案 1 :(得分:0)

原来我正在使用我的makefile运行我的Dr. Memory工具,忘了将$(ARGS)包含在我的make runmem目标中:

FLAGS = -Wall -std=c++11 -pedantic
LIBS = -Iinclude
SRC = src/xword.cpp
TGT = bin/test.exe
ARGS = human prothean vorcha krogan asari salarian turian batarian quarian

all:
    g++ $(SRC) -o $(TGT) $(FLAGS) $(LIBS)

run:
    $(TGT) $(ARGS)

runmem:
    drmemory -batch $(TGT) **$(ARGS)** # was missing

这就是Dr.Memory封装执行期间argv为空的原因,以及为什么代码只会在这些执行期间崩溃。

在此处向$(ARGS)添加makefile后,没有任何内容崩溃,也没有报告任何错误/泄漏。

对于鹅追逐感到抱歉,感谢您的帮助 - 如果这是一个应该删除的冗余帖子,请告诉我。