整数增量(++)崩溃应用程序

Tho*_*ris 1 c

我正在尝试用C编写一个小程序,但我一直试图增加一个int.

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


char * compress(char *input, int size){

    char *inputCopy;
    char compressedString[100];
    snprintf(inputCopy, size, "%s", input);
    int i = 0;
    int counter;
    int j;

    while(i < size){
        counter = 1;
        j = i;
        while (inputCopy[j] == inputCopy[j + 1] && j < size){
            j++;
            printf("same! \n");
            counter++; // When this line is commented out it works.
        }
        if (i != j){
            i = j;
        }else{
            i++;
        }

    }

    return inputCopy;
}

main(){
    char test[10] = "aaaaaaasdd";
    printf("%s \n", compress(test, 10));
    printf("%s", test);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

counter++条线由于某种原因使我的程序崩溃.我知道这可能很简单,但有人能指出我为什么这不起作用?

Bat*_*eba 6

您需要先检查j < size加强它,j + 1 < size否则您将面临越界数组访问的风险,这是未定义的行为:

while (j + 1 < size && inputCopy[j] == inputCopy[j + 1]){
Run Code Online (Sandbox Code Playgroud)

(&&如果j + 1 < size是1 ,则仅评估右手参数.)

分配的内存在哪里inputCopy


Ste*_*ell 5

你没有为其分配数据snprintf. inputCopy是未初始化的,所以它可能是在写入使用的内存counter.确保分配必要的内存.

与此崩溃无关,但您可能存在无效读取(inputCopy[j + 1]).切换j < size(j + 1) < size并将其移动到开头,while这样你就会短路.

valgrind (或Clang的地址清理程序)可以帮助您解决这两个问题,如果您使用的是Linux系统.