由于strncpy检测到堆栈粉碎

时间:2013-11-08 15:10:27

标签: c string text tokenize strncpy

我在c程序中遇到问题。我创建了一个函数,它从文本文件中标记变量并将它们保存在一个集合中。问题是string.h中的strncpy函数在我的程序中表现得很奇怪。我将代码分解为最小的例子:

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

void tokenizeWord(int *i, char *text);

int main() {
    char *text = "hallo 123 test foo bar etc";
    int i;
    for (i = 0; i < 24; i++) {
        switch(text[i]){
            case ' ':
                i++;
            default:
                tokenizeWord(&i, text);

        }
    }
    return 0;
}

void tokenizeWord(int *i, char *text) {
    bool eow = false;
    int start = *i;
    int end = start;
    if (i != NULL) {
        while (*i < strlen(text) && !eow)  {
            switch(text[*i]) {
                case ' ':
                    end = (*i);
                    eow = true;
                    break;
                default:
                    (*i)++;
                    break;
            }
        }
        char out[8] = "";
        strncpy(out, text+start, end);
        out[end-start] = '\0';
        printf("%s\n", out);
    }
}

打印出的第一个变量是&#34; hallo&#34;,什么是完全正确的行为。 secound变量已包含&#34; 123 test&#34;。但是因为我在123之后设置了\ 0,其余的不会被打印出来。在打印之后,我立刻得到 *堆栈粉碎检测* 中止。我认为问题是,strncpy函数尝试写入超过8个字符,但我告诉函数从位置6到9的文本打印。那么为什么strncpy尝试复制超过三个字符?

我没有太多的C编程经验,并尝试过很多东西,比如调试和打印输出以找到问题,但我还没有任何线索。我希望有人可以帮助我。

1 个答案:

答案 0 :(得分:0)

更改以下内容

strncpy(out, text+start, end);

strncpy(out, text+start, end-start); 

如果start = 6且end = 9,则表示您正在复制9个字节,而不是3个。

详细了解Stack Smashing