[英]Access violation reading location C++ char vector
I'm newbie in C++, and I'm having some problems with this new language :) I can't find where I am not working ok with the memory, because I never have worked with a language that don't manage the memory by itself.我是 C++ 新手,我在使用这种新语言时遇到了一些问题 :) 我找不到我在内存中无法正常工作的地方,因为我从未使用过不管理内存的语言通过它自己。 I hope someone can help me.我希望有一个人可以帮助我。
The error is "Access violation reading location".错误是“访问冲突读取位置”。
Sorry for my bad English, I'm Uruguayan.抱歉我的英语不好,我是乌拉圭人。
dopartial: test edx,1 jz short doword ***mov al,[edx]*** //here i get the error
int CalcularCantPalabras(char* str, int largo, char* delimitador){
int largo_VectorRetorno = 0;
char *palabra_cortada = new char[largo]+1;
strcpy_s(palabra_cortada ,largo+1,str);
palabra_cortada = strtok(palabra_cortada,delimitador);
while( palabra_cortada!= NULL ){
palabra_cortada = strtok(NULL,delimitador);
largo_VectorRetorno++;
}
return largo_VectorRetorno;
}
char** splitStr(char* str, char separador, int &largoRet){
char *delimitador = new char[1];
delimitador[0] = separador;
int largo_string = strlen(str);
char* str_copia = new char[largo_string];
strcpy_s(str_copia,largo_string+1,str);
int largo_VectorRetorno = CalcularCantPalabras(str_copia,largo_string,delimitador);
char ** VectorRetorno = new char*[largo_VectorRetorno];
largoRet = largo_VectorRetorno;
int posicion_vec_retorno = 0;
str_copia = strtok(str_copia-1,delimitador);
VectorRetorno[posicion_vec_retorno] = str_copia;
posicion_vec_retorno = posicion_vec_retorno+1;
while( str_copia!= NULL && posicion_vec_retorno<largo_VectorRetorno){
posicion_vec_retorno++;
str_copia = strtok(NULL,delimitador);
VectorRetorno[posicion_vec_retorno] = str_copia;
}
return VectorRetorno;
}
char *palabra_cortada = new char[largo]+1;
This should be:这应该是:
char *palabra_cortada = new char[largo+1];
Because your +1
is outside the []
, it has no effect on the size of the array.因为您的+1
在[]
之外,所以它对数组的大小没有影响。 So largo
is the size, not largo+1
.所以largo
是大小,而不是largo+1
。 Then you get hit by a double whammy.然后你会受到双重打击。 new char[largo]
is performed and gives you a pointer to the first element of the array. new char[largo]
并为您提供指向数组第一个元素的指针。 You then accidentally add 1, which is moving the pointer to the second element of the array.然后您不小心添加了 1,这会将指针移动到数组的第二个元素。
Instead of your array going from 0
to largo+1
, it goes from 1
to largo
.你的数组不是从0
到largo+1
,而是从1
到largo
。 Effectively, your array is short two elements.实际上,您的数组只有两个元素。 This is most likely the root of your problem.这很可能是您问题的根源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.