gpt4 book ai didi

c - strtol 有什么问题吗?

转载 作者:行者123 更新时间:2023-11-30 18:16:42 25 4
gpt4 key购买 nike

我有这段代码,应该可以正常运行,但由于某种原因,当我在循环的条件检查之前释放字符串时,循环会循环。摆脱循环的唯一方法是给出超过 3 位的整数(输入 > 99 || 输入 < -99)。我使用 gcc 和 code::blocks 作为 IDE 来编译此代码。

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

char* createString(void);

int main() {

int temp = 0;
char* string = 0;
char* error = 0;

do {
printf("\n Integer: ");
string = createString();
temp = strtol(string, &error, 10);
if (*error != '\n' && *error != '\0') printf("\n Input is not an integer");
free(string);
string = 0;
} while (*error != '\n' && *error != '\0');
free(error);
error = 0;
return 0;
}

char* createString() {

char* string = 0;
size_t size = 0;
size_t index = 0;
int ch = EOF;

do {
ch = getc(stdin);
if (ch == EOF || ch == '\n') ch = 0;
if (size <= index) string = (char*) realloc(string, size += 5);
if (!string) {
perror("realloc");
exit(EXIT_FAILURE);
}
string[index++] = ch;
} while(ch);
return string;
}

我通过将释放过程移至循环周期的开始和循环之后来解决这个问题。

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

char* createString(void);

int main() {

int temp = 0;
char* string = 0;
char* error = 0;

do {
free(string);
string = 0;
printf("\n Integer: ");
string = createString();
temp = strtol(string, &error, 10);
if (*error != '\n' && *error != '\0') printf("\n Input is not an integer");
} while (*error != '\n' && *error != '\0');
free(string);
string = 0;
free(error);
error = 0;
return 0;
}

char* createString() {

char* string = 0;
size_t size = 0;
size_t index = 0;
int ch = EOF;

do {
ch = getc(stdin);
if (ch == EOF || ch == '\n') ch = 0;
if (size <= index) string = (char*) realloc(string, size += 5);
if (!string) {
perror("realloc");
exit(EXIT_FAILURE);
}
string[index++] = ch;
} while(ch);
return string;
}

代码现在工作正常,但我想知道 strtol 在做什么。

最佳答案

free(error);

删除它。 error 未分配在 strtol 或其他任何地方。它是一个指向string中间的指针。释放它就是 UB。

关于c - strtol 有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23423776/

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