gpt4 book ai didi

c - 如何在c中初始化值

转载 作者:行者123 更新时间:2023-11-30 20:51:37 26 4
gpt4 key购买 nike

我开始使用 learncodethehardway 书学习 C。有一个exercise在那里谈论 valgrind。最后它要求“修复” valgrind 错误。该程序非常简单,但无论我尝试什么,valgrind 都会抛出

Use of uninitialised value of size
Conditional jump or move depends on uninitialised value(s)

网上查了一下,没有找到相关的解决方案。我使用malloc来初始化内存,但这也不起作用。任何指示都会非常有帮助。

#include<stdlib.h>

int main( int c, char *argv[]){

int age = malloc(sizeof(int));
age = 12;
int height = 12;

printf("I am %d years old.\n",age);
printf("I am %d inches tall.\n",height);

return 0;
}

根据下面提供的解决方案,我更新了代码,更新的代码:

#include<stdlib.h>

int main( int c, char **argv[]){

int* age = malloc(sizeof(int));
*age = 12;
int* height = malloc(sizeof(int)) ;
*height = 23;

printf("I am %d years old.\n",age);
printf("I am %d inches tall.\n",height);

free(age);
free(height);
return 0;
}

错误:

   ==19385== Memcheck, a memory error detector
==19385== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==19385== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==19385== Command: ./ex4
==19385==
I am -16775192 years old.
==19385== Use of uninitialised value of size 8
==19385== at 0x4E71EBB: _itoa_word (_itoa.c:195)
==19385== by 0x4E73E96: vfprintf (vfprintf.c:1622)
==19385== by 0x4E7D169: printf (printf.c:35)
==19385== by 0x40053D: main (ex4.c:9)
==19385==
==19385== Conditional jump or move depends on uninitialised value(s)
==19385== at 0x4E71EC5: _itoa_word (_itoa.c:195)
==19385== by 0x4E73E96: vfprintf (vfprintf.c:1622)
==19385== by 0x4E7D169: printf (printf.c:35)
==19385== by 0x40053D: main (ex4.c:9)
==19385==
==19385== Conditional jump or move depends on uninitialised value(s)
==19385== at 0x4E73FAA: vfprintf (vfprintf.c:1622)
==19385== by 0x4E7D169: printf (printf.c:35)
==19385== by 0x40053D: main (ex4.c:9)
==19385==
==19385== Conditional jump or move depends on uninitialised value(s)
==19385== at 0x4E73FC8: vfprintf (vfprintf.c:1622)
==19385== by 0x4E7D169: printf (printf.c:35)
==19385== by 0x40053D: main (ex4.c:9)
==19385==
I am 0 inches tall.
==19385==
==19385== HEAP SUMMARY:
==19385== in use at exit: 0 bytes in 0 blocks
==19385== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==19385==
==19385== All heap blocks were freed -- no leaks are possible
==19385==
==19385== For counts of detected and suppressed errors, rerun with: -v
==19385== Use --track-origins=yes to see where uninitialised values come from
==19385== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 4 from 4)

最佳答案

malloc函数用于在堆上分配内存,并返回一个指向内存的指针。因此,age不应该是 int ,它应该是一个指向 int 的指针,或者 int* :

int* age = malloc(sizeof(int));

然后,您需要分配到引用的位置 age ,所以你需要取消引用 age使用*运算符:

*age = 12;

虽然对于这样一个简单的程序来说这并不重要,但您还应该在程序终止之前释放堆上分配的所有内存,以避免内存泄漏(尽管当您程序退出时,操作系统会自动释放所有内存) )。

只需将以下行放在 return 之前声明:

free(age);

关于c - 如何在c中初始化值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28230670/

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