gpt4 book ai didi

c - 为什么我的 C 代码在 Windows 中出错? Linux 没问题

转载 作者:太空宇宙 更新时间:2023-11-04 05:25:15 25 4
gpt4 key购买 nike

这是我的C代码,它是leetcode problem ,我得到了“运行时错误”。所以我在VS2013中重新编译,问题是free(++tmp),为什么?看不懂,我就这样写了C代码,只是想多了解一些指针的知识。

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

/* Add binary.
* a = "11", b = "1"
* result = "100"
*/

char *add_binary(char *a, char *b);

int main()
{
printf("%s\n", add_binary("10", "1"));
printf("%s\n", add_binary("1111", "1111"));
return 0;
}

char *add_binary(char *a, char *b)
{
int alen = 0, blen = 0, sum = 0;
int len;
char *tmp, *result;

while(*a++) alen++;
while(*b++) blen++;
a -= 2;
b -= 2;
len = alen > blen ? alen : blen;
tmp = (char *)malloc(len*sizeof(char));
printf("%p\n", tmp);

while(*a || *b){
if(*a){
sum += *a - '0' + 0;
a--;
}
if(*b){
sum += *b - '0' + 0;
b--;
}
if(sum > 1){
*tmp++ = 3 == sum ? '1' : '0';
sum = 1;
} else {
*tmp++ = 1 == sum ? '1' : '0';
sum = 0;
}
}
*tmp = '\0';

len += 1 == sum ? 1 : 0;
result = (char *)malloc(len*sizeof(char));
if(1 == sum){
*result++ = '1';
}
while(*(--tmp)){
*result++ = *tmp;
}
*result = '\0';
printf("%p\n", tmp);
free(++tmp);
tmp = NULL;
return (result-len);
}

最佳答案

您只能将 malloc 的结果指针值传递给 free:

tmp = (char *)malloc(len*sizeof(char));

然后

free(tmp);

没问题。

但是 free(++tmp)free(tmp + 42) 不正常,会调用未定义的行为。

关于c - 为什么我的 C 代码在 Windows 中出错? Linux 没问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31477397/

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