[英]free() function causes a breakpoint
{
char name_entry[ARRAY_SIZE];//bunu dinamik olarak atamıyorum her seferinde gireceğimiz ismin uzunluğunu sormak pratik olmayacaktır
int isimsayisi;
char** names;
printf("Kac Isim Gireceksiniz:");
scanf("%d", &isimsayisi);
names = (char**)malloc(sizeof(char) * (isimsayisi));
for (int k = 0; k < isimsayisi; k++) {
printf("\nismi giriniz :");
scanf("%s", name_entry);
names[k] = (char*)malloc(strlen(name_entry) + 1);
if (names[k] == NULL) {
printf("bellek yetersiz!..\n");
exit(EXIT_FAILURE);
}
strcpy(names[k], name_entry);
}
printf("\nGirilen Isimler : \n");
for (int k = 0; k < isimsayisi; k++) {
printf("%s \n", names[k]);
}
printf("\n");
for (int i = 0; i < isimsayisi; i++)
free(names[i]);
_getch();
}
In this code Im try to take names to a 2d string array then printf what have ı took from user then deallocate the memory but ı cant if I print free(names);在这段代码中,我尝试将名称命名为 2d 字符串数组,然后 printf 从用户那里获取了什么然后释放 memory 但如果我打印 free(names); after the for loop it gives a windows tab error.在 for 循环之后,它给出了 windows 选项卡错误。 Its work like that to 2 names if I take more then 2 names its causes a breakpoint Edit:isimsayisi means how much names the users wants to enter如果我取 2 个以上的名称,它的工作类似于 2 个名称,它会导致断点编辑:isimsayisi 表示用户想要输入多少名称
This这个
names = (char**)malloc(sizeof(char) * (isimsayisi));
should be应该
names = malloc(sizeof(char *) * (isimsayisi));
malloc()
in C (different story for C++).您不需要在 C 中强制转换malloc()
(C++ 的情况不同)。names
is char **
; names
是char **
; therefore, when allocating memory, you need to use the sizeof(char *)
, which is definitely different than sizeof(char)
.因此,在分配 memory 时,需要使用sizeof(char *)
,这与sizeof(char)
肯定不同。 sizeof(char)
is the size of a single character and is guaranteed to be 1, while sizeof(char *)
is the size of an address and varies based on your machine (8 for a 64-bit CPU). sizeof(char)
是单个字符的大小,保证为 1,而sizeof(char *)
是地址的大小,因您的机器而异(64 位 CPU 为 8)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.