简体   繁体   中英

C - program crashes after free() is called

I've been exercising and experimenting around lately with pointers, bitwise operations, malloc, etc. while following a tutorial and encountered a crash that I do not know how to fix (without removing free()).

The tutorial code is the same as mine with the exact same free() function and for them it works.

This is the code:

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

char *convertBase(unsigned int InNumber, int base, char *pConvertedNumber){

    char hexVal[]="0123456789ABCDEF";

        if(base<2 || base>16){
            printf("Enter a base between 2 and 16");
            exit(1);
        }

    *pConvertedNumber = '\0';

    do{

        int value = InNumber % base;

        pConvertedNumber = pConvertedNumber - 1;

        *pConvertedNumber = hexVal[value];

        InNumber/=base;

    }while(InNumber !=0);

    return pConvertedNumber;

}

void main(){

    unsigned int six = 6;
    unsigned int seven = 7;

    char *pConvertedNumber;
    pConvertedNumber = malloc(33 * sizeof(char));

    unsigned int AND = six & seven;

    printf("%s & ", convertBase(six, 2, pConvertedNumber));
    printf("%s = ", convertBase(seven, 2, pConvertedNumber));
    printf("%s \n\n", convertBase(AND, 2, pConvertedNumber));

    free(pConvertedNumber);
}

You invoked undefined behavior by moving pointer to out-of-range at the line

pConvertedNumber = pConvertedNumber - 1;

Try changing three pConvertedNumber that are passed to convertBase to pConvertedNumber + 32 so that the pointer aritimetic won't go out-of-range.

Also note that you should use standard int main(void) in hosted environment instead of void main() , which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use non-standard signature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM