Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 地址边界错误_C_Memory - Fatal编程技术网

C 地址边界错误

C 地址边界错误,c,memory,C,Memory,UPD2: 该算法生成超出分配范围的字节。所以这是一个逻辑错误 UPD: 将printf修改为 printf("%d\n", bytes); 但结果是一样的——SIGSEGV 我是纯c编码的新手。这是一款简单的近邻hello world应用程序: #include <stdint.h> #include <stdio.h> #include <stdbool.h> void encode2(int src){ unsigned char * re

UPD2: 该算法生成超出分配范围的字节。所以这是一个逻辑错误

UPD: 将printf修改为

printf("%d\n", bytes);
但结果是一样的——SIGSEGV

我是纯c编码的新手。这是一款简单的近邻hello world应用程序:

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


void encode2(int src){
    unsigned char * result =(unsigned char *) malloc(sizeof(unsigned char) *10);
    int bytes = 0;
    bool More;
    do{
        uint8_t Byte = src & 0x7f;
        src >> 7;
        More = !((((src == 0) && ((Byte & 0x40) == 0)) ||
                  ((src == -1) && ((Byte & 0x40) != 0))));
        if (More)
            Byte |= 0x80;
        result[bytes] = Byte;
        bytes++;
    } while(More);
    printf(bytes);
    unsigned char * str = (unsigned char *) malloc(sizeof(unsigned char) * bytes);
    int i;
    for (i=0; i<bytes; i++){
        str[i] = result[i];
    }
}

int main(int argc, char *argv[]){
    encode2(10);
    /*printf("%s\n",p);*/
    return 0;
}
作业1“./leb128”因信号SIGSEGV地址边界错误而终止

试图用谷歌搜索SIGSEGV,但找不到有什么问题?

SIGSEGV只是告诉您,您已访问内存,但尚未分配内存。在while循环之后直接调用printf会导致SIGSEGV

printf的第一个参数是char*,它将格式字符串作为以null结尾的字符数组指向。比方说,字节数是2。然后C将2解释为内存地址,并在printf中尝试读取地址0x0000000000000002处以null结尾的字符串。这很可能是您无法访问的

我想,你的意思是有printf%d\n,字节


请注意,您必须释放使用malloc分配的所有内存。C语言中没有垃圾收集器,所以所有分配的内存都会一直保留,直到再次释放它。您不希望在长时间运行的进程中出现这种情况。

您需要检查do-while循环 因为在这个bool More中永远不会设置为false,因为您正在访问额外的内存结果[bytes]=Byte;
所以您得到了错误。

。结果[bytes]的界限在哪里?printfbytes;。。。。。你不能这么做。对不起,什么意思?边界在哪里我分配了10个字符的数组。这是我理解的界限。我修改了printf。同样的结果。你在SIGSEGV之前从printf得到输出了吗?如果不是的话,我猜,你对更多的计算是错误的,你写下了过去的结果[9]。