地址边界错误

时间:2015-10-13 06:26:50

标签: c memory

UPD2: 算法从分配的范围中生成字节。所以这是一个合乎逻辑的错误。

UPD: 修改了printf到

printf("%d\n", bytes);

但结果是一样的 - SIGSEGV。

我是纯c编码的新手。这很简单"你好世界"应用程式:

#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;
}
  

Job 1,&#39; ./ leb128&#39;信号SIGSEGV(地址边界错误)终止

试图谷歌SIGSEGV,但无法找到什么错误?

2 个答案:

答案 0 :(得分:2)

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

printf()的第一个参数是char*,它将格式字符串指向以空字符结尾的字符数组。让我们说,bytes是2.然后C将2解释为内存地址,并在printf()尝试读取地址为0x0000000000000002的空终止字符串。这很可能是你无法访问的。

我想,你的意思是printf("%d\n", bytes);

请注意,您必须free()使用malloc()分配的所有内存。 C中没有垃圾收集器,因此您分配的所有内存都会保留,直到再次free()为止。在长时间运行的流程中,您不希望这样。

答案 1 :(得分:1)

你需要检查你的do while循环 因为在bool More永远不会设置false,因为你正在访问额外的内存(result[bytes] = Byte; )所以你得到错误。