调试器显示错误值指针 [英] Debugger shows wrong value to pointer

查看:133
本文介绍了调试器显示错误值指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

#include <iostream>
#include <cstdio>
#include <list>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <unordered_set>
#include <unordered_map>
#include <limits>
#include <functional>
#include <algorithm>
#include <cmath>
#include <string>
#include <ostream>
#include <sstream>
#include <bitset>
#include <numeric>
#include<fstream>



using namespace std;

char str[] = "this.is.a.test";
char str2[] = "this.is.another.test";

typedef struct
{
    size_t count;
    char** strings;
} Tokens;

Tokens Tokenize(char* String, char Split)
{
    Tokens t;
    t.count = 1;

    for (size_t i = 0; String[i] != 0; i++)
    {
        if (String[i] == Split)
            t.count++;
    }

    t.strings =(char**) malloc(sizeof(char*)* t.count);

    if (t.count > 0)
        t.strings[0] = String;

    for (size_t i = 0, j = 1; String[i] != 0; i++)
    {
        if (String[i] == Split)
        {
            t.strings[j] = &String[i + 1];
            String[i] = 0;
            j++;

        }
    }


    return t;
}

int main(void)
{
    Tokens t = Tokenize(str, '.');
    printf("number of strings: %i\n---\n", t.count);
    for (size_t i = 0; i < t.count; i++)
    {
        printf("%i: %s\n", i, t.strings[i]);
    }
    free(t.strings);

}

问题是,当我调试code和特别是该行 t.strings [J] =&放大器;字符串[I + 1];

在this.is.a.test测试用例

In a test case of this.is.a.test

目前找到的第一个点。 ,应当指出这一点,但在调试它显示以下的画面。

    在此输入code

At the first found dot . , it should points to this, but in the debugger it shows the following picture. enter code here

推荐答案

什么是调试器显示是正确的路线55.转让确已作出,所以 t.strings [J] 点的点之后。

What the debugger shows is correct at line 55. The assignment has been made, so t.strings[j] points after the dot.

请注意,在标记化你分配标记吨; 堆栈,后来返回该 T 。这是坏的(非常糟糕的!)。因为 T 是在栈上,将通过调用覆盖到的printf

Note that in Tokenize you allocate Tokens t; on the stack and later return this t. That is bad (very bad!). Because t is on the stack, it will be overwritten by the call to printf.

(虽然大多数是C,形式上是C ++与C不能声明在初始化的变量,如为(为size_t I = 0;

(And although most is C, formally it is C++ as in C you cannot declare a variable in the for initialization, as in for (size_t i = 0;)

这篇关于调试器显示错误值指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆