【问题标题】:Stack smashing detected in C - why does this happen?在 C 中检测到堆栈粉碎 - 为什么会发生这种情况?
【发布时间】:2023-01-08 03:28:09
【问题描述】:

我有以下函数,给定一个字符串,它应该在其中找到最常见的几个字母并将结果存储在不同的字符串中。 例如 - 对于字符串“ababa”,最常见的一对是“ba”,而对于“excxexd”,它将是“ex”。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

void printError(){
    printf("Error: please check your input\n");
}

bool isLexicographicallyPreceding(char couple1[], char couple2[])
{
    if (strcmp(couple1, couple2)>=0) return true;
    return false;
}

void coupleDetector(int length, char word[], char result[])
{
    char couples[length-1][2];
    for (int i=0; i<length-1; i++)
    {
        char couple[2] = {word[i], word[i+1]};
        strcpy(couples[i], couple);
    }
    char element[]="";
    int count=0;
    for (int j=0; j<length-1; j++)
    {
        char tempElement[2];
        strcpy(tempElement,couples[j]);
        int tempCount=0;
        for (int p=0; p<length-1; p++)
        {
            if (couples[p]==tempElement) tempCount++;
        }
         if (tempCount>count)
            {
                strcpy(element, tempElement);
                count=tempCount;
            }
            if (tempCount==count)
            {
                if (isLexicographicallyPreceding(tempElement,element) == true) strcpy(element, tempElement);
            }
    }
    strcpy(result,element);
}

int main() {
    //Supposed to print "ba" but instead presents "stack smashing detected".
    int length=5;
    char arr[] = "ababa";
    char mostCommonCouple[2];
    coupleDetector(length,arr,mostCommonCouple);
printf("%s", mostCommonCouple);
    return 0;
}

代码编译没有错误,但由于某种原因没有按预期工作,而是打印出“检测到堆栈粉碎”。为什么会这样?建议会很有帮助。 谢谢。

【问题讨论】:

  • 风格说明:自然陈述:if (boolean_expression) then return true; else return false; 可以只是return boolean_expression;
  • 你把所需的 NUL 终止符放在char mostCommonCouple[2]; 的什么地方?
  • C 字符串是终止字符序列。你是两个字符的字符串操作不为终止符保留空间。任何关于 C 语言的文本,即使是较差的文本,都涵盖了字符串在 C 中的表示方式和字符串操作的工作方式。

标签: arrays c string pointers stack


【解决方案1】:

在试用您的程序时,我发现您的一些字符数组尺寸过小。字符数组(字符串)的大小需要足够大,以便在数组中也包含空终止符值。因此,在许多位置,具有两个字符的数组大小是不够的,并且是堆栈崩溃的原因。考虑到这一点,以下是您程序的重构版本。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

void printError()
{
    printf("Error: please check your input
");
}

bool isLexicographicallyPreceding(char couple1[], char couple2[])
{
    if (strcmp(couple1, couple2)>=0) return true;
    return false;
}

void coupleDetector(int length, char word[], char result[])
{
    char couples[length-1][3];
    for (int i=0; i<length-1; i++)
    {
        char couple[3] = {word[i], word[i+1], '
猜你喜欢
  • 1970-01-01
  • 2012-05-31
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
相关资源
最近更新 更多