2

UPD2: The algoritm generates bytes out of allocated range. So it's a logical mistake.

UPD: modifyed printf to

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

But the result is same - SIGSEGV.

I am new in pure c coding. This is simple near "hello world" app:

#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, './leb128' terminated by signal SIGSEGV (Address boundary error)

Tried to google SIGSEGV but couldn't found whats wrong?

nvoigt
  • 75,013
  • 26
  • 93
  • 142
user3003873
  • 543
  • 1
  • 4
  • 21

2 Answers2

3

A SIGSEGV just tells you, that you have accessed memory, you have not allocated. Your call to printf() directly after the while loop causes that SIGSEGV.

The first parameter to printf() is a char*, that points to the format string as a null-terminated character array. Let's say, bytes is 2. Then C will interpret 2 as a memory address and in printf() try to read the null terminated string that is at address 0x0000000000000002. That is most probably not accessible for you.

I guess, what you mean there is printf("%d\n", bytes);

Please be aware, that you'll have to free() all the memory, you have allocated using malloc(). There is no garbage collector in C, so all the memory you allocate stays around untill you free() it again. You don't want that in longer running processes.

cdonat
  • 2,748
  • 16
  • 24
2

You need to check your do while loop because in that bool More never going to set false, because of that you are accessing extra memory (result[bytes] = Byte; ) so you getting error.

Mohan
  • 1,871
  • 21
  • 34