Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C程序中的奇怪行为,分配内存后变量损坏_C_String_Malloc - Fatal编程技术网

C程序中的奇怪行为,分配内存后变量损坏

C程序中的奇怪行为,分配内存后变量损坏,c,string,malloc,C,String,Malloc,我的C程序中有一个字符串的typdef,它看起来像: #define WRD_LEN 100 typedef char cstring[WRD_LEN]; 然后在某个时刻,我声明了这种类型的动态数组: int pcount = 1; cstring *options = malloc(sizeof(cstring*)*pcount); 我使用realloc将新字符串添加到此数组: options = realloc(options, sizeof(cstring*)*pcount); str

我的C程序中有一个字符串的typdef,它看起来像:

#define WRD_LEN 100
typedef char cstring[WRD_LEN];
然后在某个时刻,我声明了这种类型的动态数组:

int pcount = 1;
cstring *options = malloc(sizeof(cstring*)*pcount);
我使用realloc将新字符串添加到此数组:

options = realloc(options, sizeof(cstring*)*pcount);
strcpy(options[pcount-1], //some string//);
pcount++;
然后将所有条目显示给用户,用户选择其中一个条目并将其传递给另一个函数:

highestof(mode, l, options[btn]);
void highestof(const int mode, List l, const cstring cat) {
List *p = malloc(sizeof(List*));
mode是一个整数,l是struct,但现在这些都不相关了。btn是用户选择的条目的编号(int)。 到目前为止,一切正常,问题出现在函数的highestof中:

highestof(mode, l, options[btn]);
void highestof(const int mode, List l, const cstring cat) {
List *p = malloc(sizeof(List*));
以下是列表的定义:

struct W {
    //some data
    struct W *next;
};
struct List {
    struct W *first;
};
因此,如果使用选项[1]调用highestof函数,cat变量将在调用malloc之后立即损坏(它将成为一组少量随机符号,如“#^?”或“^K^?”),即在创建列表的动态数组之前,我可以随意使用cat,但是调用malloc后,它会被损坏。最奇怪的是,只有当传递给该函数的变量位于索引为1(options[btn]其中btn=1)的options数组中时,才会发生这种情况。对于btn的任何其他值,它都可以正常工作


我找到了一个解决方法,在调用malloc之前,我可以创建一个字符串(char s[100]),将cat值复制到其中并使用该变量,但这并不能解决最初的问题,它真的让我很困扰。

cstring*
只是一个指针,通常是四个或八个字节<因此,code>sizeof(cstring*)是一个小数字,通常为四或八


您没有为数据分配足够的内存,只分配足够的内存来保存指向数据的指针

cstring*只是一个指针,通常是四个或八个字节<因此,code>sizeof(cstring*)是一个小数字,通常为四或八

您没有为数据分配足够的内存,只分配足够的内存来保存指向数据的指针

sizeof(cstring*)*pcount
太小。尺寸计算错误


避免分配错误。对于更易于正确编写、检查和维护的代码,请使用此习惯用法。
请注意,未使用任何类型

然后代码变成:

// options = malloc(sizeof(cstring*)*pcount);
options = malloc(sizeof *options * pcount);`
sizeof(cstring*)*pcount
太小。尺寸计算错误


避免分配错误。对于更易于正确编写、检查和维护的代码,请使用此习惯用法。
请注意,未使用任何类型

然后代码变成:

// options = malloc(sizeof(cstring*)*pcount);
options = malloc(sizeof *options * pcount);`

它应该是
sizeof(cstring)
,而不是
sizeof(cstring*)
sizeof
参数的
*
值应始终比指定给它的指针少一个。@Barmar不同意。我建议使用带有指针的
*
,而不是像
sizeof*options*pcount
@chux那样移动指针类型,这是另一种方法。但是,如果您使用该类型,它应该少一个
*
。它应该是
sizeof(cstring)
,而不是
sizeof(cstring*)
sizeof
参数的
*
值应始终比指定给它的指针少一个。@Barmar不同意。我建议使用带有指针的
*
,而不是像
sizeof*options*pcount
@chux那样移动指针类型,这是另一种方法。但是如果你使用这个类型,它应该少一个
*
.Nitpick:“
cstring*
只是一个指针”不是很好
cstring*
是一种指针类型。吹毛求疵:“
cstring*
只是一个指针”不是很正确
cstring*
是指针类型。