Search code examples
csegmentation-faultmallocmemsetunsigned-char

c++ unsigned char array allocation - segmentation fault


I can't figure out what seems to be the problem that I get a segmentation fault from this:

#include <stdio.h>
#include <stdlib.h>
#include <cstring>

void alloc(unsigned char *data) {
    data = (unsigned char *) malloc(20);
    memset(data, 0, 20);
}

void main() {
    unsigned char *data = NULL;
    int i;
    alloc(data);
    for (i = 0; i < 20; i++) {
        data[i] = i;
        printf("%d ", *(data + i));
    }
    free(data);
}    

Unsigned char is 1 byte so the loop through 20 should be correct


Solution

  • It seems that your program is written in C instead of C++. In C++ you should use operator new [] instead of malloc.

    The problem with the function is that function parameters are its local variables. So the function parameter char *data is a copy of its argument declared in main like

    unsigned char *data = NULL;
    

    So any changes of the parameter in function alloc do not influence on the original argument. After exiting the function the parameter (local variable) will be destroyed and the original variable in main will not be changed.

    You have two approaches. Either you declare the function the following way

    void alloc(unsigned char **data) {
        *data = (unsigned char *) malloc( 20 );
        if ( *data ) memset( *data, 0, 20 );
    }
    

    and call it like

    alloc( &data );
    

    Or you declare the function the following way

    unsigned char * alloc() {
        unsigned char *data = (unsigned char *) malloc( 20 );
    
        if ( data ) memset( data, 0, 20 );
    
        return data;
    }
    

    and call it in main like

    data = alloc();
    

    Take into account that function main shall be decalred in C like

    int main( void )
    ^^^
    

    and in C++ like

    int main()
    ^^^