gpt4 book ai didi

c - malloc 不能正常工作?

转载 作者:太空宇宙 更新时间:2023-11-04 06:18:46 24 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>
void func(char *p[],int);
void main()
{
char **strings;
int r;
printf("\nEnter the no. of rows :");
scanf("%d",&r);
strings=malloc(r*sizeof(strings));
func(strings,r);
printf("%s %s\n", strings[0], strings[1]);
}

void func(char *p[],int r)
{
int i;
for(i=0;i<r;i++)
scanf("%s",p[i]);
}

此代码不接受超过 3 个输入...在 3 个输入后,它突然停止。

为什么 malloc 不能正常工作?仅仅是因为 malloc 吗?

最佳答案

问题在于您如何使用 malloc。您没有分配足够的内存,而且您不知道要分配多少内存。

strings=malloc(r*sizeof(strings));

这会在 strings 中为 r 字符指针 分配足够的内存。 strings 现在可以安全地存储类型为 char *r 变量。问题是您永远不会为存储在 strings 中的字符串分配内存。

void func(char *p[],int r)
{
int i;
for(i=0;i<r;i++)
/* At this point, p[i] is unallocated */
scanf("%s",p[i]);
}

p[i],实际存储字符串的东西,也必须分配。多少?谁知道呢,您正在使用 scanf 从输入中读取。所以第一步是分配一个固定的大小,并且最多只读取该大小(由于空字符而减少一个)。

void func(char *p[],int r)
{
int i;
for( i=0; i < r; i++ ) {
p[i] = malloc( 256 * sizeof(char) );
scanf("%255s",p[i]);
}
}

切勿使用没有最大长度的scanf %s,否则输入可能会大于您分配的内存。还有 don't use scanf ,如果输入与您的模式不匹配,它会给您带来麻烦。最好使用 getlinefgets 读取整行,然后在必要时使用 sscanf


在用 C 编写代码时,内存检查器是绝对必要的。它会为您发现这些问题。我用 valgrind .

Enter the no. of rows :5
foo
==10082== Use of uninitialised value of size 8
==10082== at 0x1001F2121: __svfscanf_l (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x1001EA979: scanf (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x100000F2B: func (test.c:19)
==10082== by 0x100000EBD: main (test.c:11)
==10082==
==10082== Invalid write of size 1
==10082== at 0x1001F2121: __svfscanf_l (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x1001EA979: scanf (in /usr/lib/system/libsystem_c.dylib)
==10082== by 0x100000F2B: func (test.c:19)
==10082== by 0x100000EBD: main (test.c:11)
==10082== Address 0x0 is not stack'd, malloc'd or (recently) free'd

那些是指向内存问题的堆栈跟踪。 “使用大小为 8 的未初始化值”告诉我未能为字符串分配内存。堆栈告诉我它是 func 中的 scanf

关于c - malloc 不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022983/

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