简体   繁体   English

C-调用free()后程序崩溃

[英]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()). 在遵循本教程的同时,我最近一直在使用指针,按位操作,malloc等进行锻炼和试验,遇到了崩溃,我不知道如何解决(不删除free())。

The tutorial code is the same as mine with the exact same free() function and for them it works. 教程代码与我的教程代码完全相同,但具有完全相同的free()函数,并且对于它们而言,它们均有效。

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. 尝试将传递给convertBase三个pConvertedNumber更改为pConvertedNumber + 32 ,以使指针的时间不会超出范围。

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. 另请注意,除非在特殊情况下使用非标准签名,否则应在托管环境中使用标准int main(void)代替void main()在C89中是非法的,并且在C99或更高版本中由实现定义)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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