gpt4 book ai didi

c - 二进制到十进制段错误

转载 作者:行者123 更新时间:2023-11-30 20:01:16 27 4
gpt4 key购买 nike

我使用指针代替数组,我知道与数组不同,指针需要被释放。为什么使用指针代替数组会给我带来分段内存错误。

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

void bin(void){

char *input;
int choice;
int x = 0;


printf("Enter Decimal Code:\n");
scanf("%s",&input);

int leng = strlen(input);



for(int i = 0; i <= leng ; ++i){

if(input[i] == '1'){
x += pow(2,i);


}
else if(input[i] == '0'){
input[i] = 0;


}
free(input);

}
printf("Binary-Dec: %d\n",x);


}

int main()
{
bin();

}

最佳答案

在你的代码中

 scanf("%s",&input);

是有问题的部分。据我所知,有两个问题。

  • 首先,input是一个指针,&input是指针的地址。
  • 其次,即使去掉&,由于input没有分配内存,仍然会导致undefined behavior .

你应该这么做

 char input[32] = {0};
scanf("%31s", input); //limit the input buffer to prevent overflow

此外,建议您检查 scanf() 的返回值是否成功,以确保输入正确。

<小时/>

FWIW,声明

[...]I'm aware that a pointer needs to be freed[..]

正确,但前提是它们通过 malloc() 或函数系列动态分配内存。考虑以下场景,

char buf[32] = {0};
char *input = buf;
. . . .

在这种情况下,您不需要以任何方式 free() 输入,因为内存不是动态分配的。更多信息,您可以引用this answer .

关于c - 二进制到十进制段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34719253/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com