c#char指针指针,char **

时间:2018-06-09 12:24:10

标签: c# pointers char

我有这个代码(snipet),它运行并运行,但在离开整个过程procedureInAClass()并继续下一个代码后,它崩溃了:“Bad_module_error”。我没有看到错误。

public void procedureInAClass(){ //this code is in a Class, it works but after leaving whole procedure it crashes
char** comment=(char**)Marshal.AllocHGlobal(sizeof(char*)); //comment is in Code a class Member
string aval="some chars in a string";
SToCP(val,  comment) ; //value of String to *comment
CPToS(comment); //**comment to string
}

//this part is in a static class

    public static void SToCP(string s, char** c)//writes string s in *c
    {      
        *c = SToCP(s);
    }
    public static char* SToCP(string s) 
    {
        char* ret= (char*)Marshal.AllocHGlobal( sizeof(char) * (s.Length +1));
        int i;
        byte se = sizeof(char);
        for (i = 0; i < s.Length; i++)
            *(ret + se * i) = s[i];
        *(ret + s.Length * se) = '\0';
        return ret;
    }



public static String CPToS(char** c)
    { 
          return CPToS(*c); //passing the pointer char* which is holded by char** c
    }

public static String CPToS(char* c)
    {
        string ret = "";
        byte s = sizeof(char);//char is two bytes long
        int i = 0;
        while (*(c + s * i) != '\0')//zero terminated string
            ret += *(c + s * i++);
        return ret;
    }

1 个答案:

答案 0 :(得分:0)

您的问题是您将索引i乘以sizeof(char*),但将其视为char*。将1添加到char *会将char(2个字节)的大小添加到指针。你正在编写其他所有角色,然后因为走得太远而继续在你的字符串分配后覆盖内存。

请改为尝试:

public static char* SToCP(string s) {
    char* ret = (char*)Marshal.AllocHGlobal(sizeof(char) * (s.Length + 1));
    char* p = ret;
    for (int i = 0; i < s.Length; i++)
        *(p++) = s[i];            
    *(p++) = '\0';
    return ret;
}

当然,您的CPToS方法也是错误的,因此如果您修复SToCP以正确地不写入其他字符,则需要修复CPToS,否则它将返回错误的回来了。

以下是CPToS的固定版本匹配:

public static String CPToS(char* c) {
            string ret = "";
            int i = 0;
            while (*(c +  i) != '\0')//zero terminated string
                ret += *(c +  i++);
            return ret;
        }

SToCP导致堆栈被搞砸并导致崩溃。