LeetCode剑指offer58——“左旋字符串”+报错AddressSanitizer:heap-buffer-overflow

该博客主要介绍了LeetCode中的剑指offer58问题,即如何进行字符串左旋转操作。博主分享了在解决过程中遇到的编译错误——未声明变量'i',以及执行时由于数组大小不足导致的AddressSanitizer: heap-buffer-overflow错误,并提供了三种错误修复方案,包括在for循环外部声明变量'i',以及适当调整数组大小以避免越界访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode——剑指offer58“左旋字符串”

【问】

字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。

示例 1:

输入: s = “abcdefg”, k = 2
输出: “cdefgab”

【解】

char* reverseLeftWords(char* s, int n)
{
    int len = strlen(s);
    //另一种写法:char *rev=(char*)malloc(sizeof(char)*(len+1));
    //+1为字符串末尾的/0留出位置!!!
    char *rev=(char *)calloc(len+1,sizeof(char));
    int a = len-n;
    int b = n;
    int i = 0;
    //错解:for( int i = 0; i < a; i++)————i在下一个for循环也要用,不能在for内声明,应在for外单独声明
    for(i = 0; i < a; i++)
    {
        rev[i] = s[b];
        b++;
    }
    for(int j = 0; j < n; j++)
    {
        rev[i] = s[j];
        i++;
    }
    return rev;
}

【笔记】

1.编译出错——int i

【错】
for(int i = 0; i < a; i++)

solution.c: In function ‘reverseLeftWords’
Line 18: Char 13: error: ‘i’ undeclared (first use in this function) [solution.c]
rev[i] = s[j];
^
【改】
int i = 0;
for(i = 0; i < a; i++)

i在下一个for循环也要用,不能在for内声明,应在for外单独声明

2. 执行出错——数组大小定义过小,导致访问越界
【错】
char *rev=(char)malloc(sizeof(char)*(len+1));

ERROR: AddressSanitizer: heap-buffer-overflow on address …

【改】

01:
#define MAX_CONTAIN 10001
char *rev=(char)malloc(sizeof(char)*(len+1));

02:
char *rev=(char )calloc(len+1,sizeof(char));
//char *rev=(char)malloc(sizeof(char)
(len+1));

03:
int len = 0;
if(s[0]==’\0’|| n<=0)
return s;
len = strlen(s); //统计s长度
char *rev=(char)malloc(sizeof(char)*(len+1));
【扩充】
AddressSanitizer: stack-buffer-overflow on address 一般都是代码哪里出现了问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值