如何解决局部变量可能指向在 Linux 上使用 CLion 的 C 中释放的内存
我正在用 C 编写一个项目,但收到此警告
局部变量可能指向释放的内存
对于下面的代码
int printSched()
{
char* schedString = (char*)malloc(strlen("cat /proc/sched\n")+sizeof(getppid()));
if (schedString) {
sprintf(schedString,"cat /proc/%d/sched\n",getppid());
int commandSize = numOfWords(schedString);
char** schedCommand = (char**) malloc((commandSize + 1) * sizeof (char*));
if(schedCommand == NULL)
{
free(schedString);
fprintf(stderr,"malloc failed");
exit(1);
}
schedCommand[commandSize] = NULL;
parseString(schedString,schedCommand);
exeCommand(schedCommand);
freeArr(schedCommand);
return 0;
}
else //malloc failed - handled in main
return -1;
}
关于这个特殊的免费命令
free(schedString);
我坚信这条消息在 CLion 最新更新到 2021.1 版本之前没有出现
我做错了什么(至少在这部分)还是 CLion 问题?
numOfWords 函数
//receives a sentence and returns the number of words in it,ignoring blank spaces,assuming it ends with '\n'
int numOfWords(const char sentence[] )
{
int i = 0,wordCounter = 0;
while(sentence[i] != '\n')
{
if(sentence[i] != ' ' && (sentence[i+1] == ' ' || sentence[i+1] == '\n'))
wordCounter++;
i++;
}
return wordCounter;
}
解决方法
我没有看到发布代码中“局部变量可能指向已释放的内存”的理由。
可能存在其他问题,但我看到了这个:
strlen("cat /proc/sched\n")+sizeof(getppid()
可能太小了。
sizeof(getppid())
是 pid_t
的字节大小,而不是它的十进制字符串大小。
更好
#define INT_STR_MAXLEN 11
strlen("cat /proc/sched\n") + INT_STR_MAXLEN + 1 /* \0 */)
甚至更好,因为 pid_t
可能比 int
更宽。 correct printf specifier for printing pid_t
调用 snprintf(NULL,...
以获得所需的大小。
pid_t pid = getppid();
int len = snprintf(NULL,"cat /proc/%jd/sched\n",(intmax_t) pid);
// assert(len > 0);
char* schedString = malloc(len + 1);
if (schedString) {
sprintf(schedString,(intmax_t) pid);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。