gpt4 book ai didi

c - 在 C 中使用带有字符数组的结构时出错

转载 作者:行者123 更新时间:2023-12-02 07:52:02 25 4
gpt4 key购买 nike

我有一个包含字符数组的结构和另一个包含该结构的结构。我通过引用初始化数组的函数来传递它。然后,我调用一个函数来打印并释放数组。

请帮我看看这个程序有什么问题?

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

typedef struct {
char *x;
double y;
} A;

typedef struct {
A a;
int w;
} B;

void f(B *b) {
int i;

b->w = 5;
b->a.x = (char *) malloc(sizeof(char) * 5);
printf("addres in f %p: \n", b->a.x);

for(i = 0; i < 5; i++)
b->a.x[i] = 'a';

b->a.y = 20;
}

void p(B *b) {
int i;

printf("w: %d\n", b->w);
printf("addres in p %p: \n", b->a.x);
printf("x: %s\n", b->a.x);
printf("y: %f\n", b->a.y);
free(b->a.x);
}

int main(int argc, char **argv) {
B b;

f(&b);
p(&b);

return 0;
}

当我使用 valgrind 运行时,会发生以下情况:

==28053== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 2)
==28053==
==28053== 1 errors in context 1 of 1:
==28053== Invalid read of size 1
==28053== at 0x3A03E489D7: vfprintf (in /lib64/libc-2.10.1.so)
==28053== by 0x3A03E4FB49: printf (in /lib64/libc-2.10.1.so)
==28053== by 0x400633: p (test_struct.c:33)
==28053== by 0x400686: main (test_struct.c:43)
==28053== Address 0x4c20035 is 0 bytes after a block of size 5 alloc'd
==28053== at 0x4A0763E: malloc (vg_replace_malloc.c:207)
==28053== by 0x400574: f (test_struct.c:19)
==28053== by 0x40067A: main (test_struct.c:42)

和输出:

addres in f 0x16b4010: 
w: 5
addres in p 0x16b4010:
x: aaaaa
y: 20.000000

谢谢, Mercurial

最佳答案

你还没有空终止你的'字符串'b->a.x所以printf("x: %s\n", b-> a.x); 读取已分配内存的末尾,这会导致您在 valgrind 中遇到错误。

您可以通过更改来修复它

b->a.x = (char *) malloc(sizeof(char) * 5);
printf("addres in f %p: \n", b->a.x);

for(i = 0; i < 5; i++)
b->a.x[i] = 'a';

b->a.x = malloc(6 * sizeof b->a.x);
printf("address in f %p: \n", b->a.x);

for(i = 0; i < 5; i++)
b->a.x[i] = 'a';
b->a.x[i] = '\0';

在这里,我将动态分配的内存块的大小增加到6,并使用 b 显式空终止“字符串” ->a.x[i] = '\0';\0 用于在 C 中空终止字符串。

<小时/>

注意:正如 @Michi 在评论中指出的那样。在 C 中,无需转换 malloc() 的结果。

我还将 sizeof(char) 重写为 sizeof b->a.x,因为在您更改 b- 的类型时,它的可移植性更好>a.x.

关于c - 在 C 中使用带有字符数组的结构时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32100071/

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