使用c的leetcode实践中的AddressSanitizer错误 char*转换(char*s,int numRows){ 字符行[numRows][strlen(s)]; memset(行,'\0',numRows*strlen*sizeof(char)); int curRow=0; 布尔下降=错误; int len=0; char*str=s; for(字符c=*str;c=*str;++str){ len=0; while(rows[curRow][len]){len++;} 行[curRow][len]=c; 如果(curRow==numRows-1 | | curRow==0){goingDown=!goingDown;} 如果(向下){curRow++;} 否则{curRow--;} } char*zig=malloc(strlen+1); *zig='\0'; int i=0; 对于(char*row;i

使用c的leetcode实践中的AddressSanitizer错误 char*转换(char*s,int numRows){ 字符行[numRows][strlen(s)]; memset(行,'\0',numRows*strlen*sizeof(char)); int curRow=0; 布尔下降=错误; int len=0; char*str=s; for(字符c=*str;c=*str;++str){ len=0; while(rows[curRow][len]){len++;} 行[curRow][len]=c; 如果(curRow==numRows-1 | | curRow==0){goingDown=!goingDown;} 如果(向下){curRow++;} 否则{curRow--;} } char*zig=malloc(strlen+1); *zig='\0'; int i=0; 对于(char*row;i,c,C,,您的问题(或至少其中一个)位于函数定义的第一行 char * convert(char * s, int numRows){ char rows[numRows][strlen(s)]; memset( rows, '\0', numRows*strlen(s)*sizeof(char) ); int curRow=0; bool goingDown=false; int len=0; char *str=s; for(char c=*str;c=*str;++str){ len=0;

,您的问题(或至少其中一个)位于函数定义的第一行

char * convert(char * s, int numRows){
char rows[numRows][strlen(s)];
memset( rows, '\0', numRows*strlen(s)*sizeof(char) );
int curRow=0;
bool goingDown=false;
int len=0;
char *str=s;
for(char c=*str;c=*str;++str){
    len=0;
    while(rows[curRow][len]){len++;}
    
    rows[curRow][len]=c;
    if(curRow==numRows-1||curRow==0){goingDown=!goingDown;}
    if(goingDown){curRow++;}
    else{curRow--;}
}
char *zig=malloc(strlen(s)+1);
*zig='\0';
int i=0;
for(char *row;i<numRows;i++){
    row=*(rows+i);
    zig=strcat(zig,row); 
}
return zig;
在堆栈上声明2D char数组。不应在堆栈中声明大小取决于运行时的变量(在本例中,由于传递给函数的变量s和numrows)

相反,您应该使用malloc或其他方法动态分配内存-

char rows[numRows][strlen(s)];
char**rows=malloc(sizeof(char*)*numrows);//分配内存存储'num_rows'字符指针
//对于行中的每个元素,创建一个指针,其中的num_列具有字符数和空间量
对于(int i=0;i
请注意,要在C字符数组中添加空终止符,需要比字符串中的字符数多分配一个字符。
这可能会消除缓冲区溢出错误,尽管您的程序可能包含其他缺陷。

您是否也在启用调试信息的情况下编译?如果未启用,请执行此操作,并包含完整的错误消息。还可以编辑您的问题,使其包含一个,而不仅仅是一个函数。人们可以复制、粘贴并在不更改的情况下运行。您应该详细说明w这段代码应该做什么。
if(curRow==numRows-1 | | curRow==0)
curRow
在第一次迭代时将为0,因此下一次您将是
!向下运行
并执行
curRow--
,然后在数组之前进行访问,这是无效的。
strcat
循环似乎使用第二个参数调用
strcat
,该参数不是以空结尾的字符串,并且几乎没有分配足够的空间这是完全错误的,对运行时大小的阵列的支持是在22年前添加的ago@M.M,您是对的,您完全可以声明一个运行时大小的数组,编译器不会抱怨。但是,它仍然存储在堆栈上。堆栈大小是有限的,应该分配动态数组,这是一个使用静态内存显示segfault的简短演示Y
char ** rows = malloc(sizeof(char *)*numrows); // allocate memory to store `num_rows` char pointers
// for each element in rows, create a pointer with num_columns of chars amount of space
for(int i = 0 ; i < num_columns ; i++){
    rows[i] = malloc(sizeof(char) * num_columns); // store pointer in rows[i]
    // memset this memory as needed
}
// now rows[x][y] will be one char