[英]free(); and malloc(); keeps crashing (C)
I built this code to practice pointers and the program keeps crashing.it seems it crashes when I enter a big number to counter
. 我建立了这段代码来练习指针,程序不断崩溃。当我输入一个大数字进行counter
时,它似乎崩溃了。 1-5 doesn't affect it apparently, but when you enter 30 it keeps crashing, sometimes on the allocation itself malloc(...
and sometime in the free(names[i]);
function. 1-5显然不会对其产生影响,但是当您输入30时,它一直崩溃,有时是在分配本身malloc(...
以及有时在free(names[i]);
函数中。
What's the problem here? 这是什么问题
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
int main() {
char **names;
char buffer[100];
int i, bufferLen, counter;
printf("how many names? ");
scanf_s("%d", &counter);
if (counter < 0) {
printf("wrong choice\n");
return 1;
}
names = (char**)malloc(77 * sizeof(char));
if (names == NULL) {
printf("failed...\n");
return 1;
}
for (i = 0; i < counter; i++) {
printf("write the name!! (up to 100 chars): \n");
gets_s(buffer, sizeof(char) * 100);
bufferLen = strlen(buffer) + 1;
names[i] = (char*)malloc(sizeof(char)*bufferLen);
if (names[i] == NULL) {
printf("failed...\n");
return 1;
}
strcpy_s(names[i], sizeof(char)*bufferLen, buffer);
}
for (i = counter-1; i >= 0; i--) { //print names
printf("no. %d, ptr no. %d (size: %d bytes): \n", i+1, (int)(names[i]), sizeof(names[i]));
puts(names[i]);
}
for (i = 0; i < counter; i++) {
if (names[i] != NULL)
free(names[i]);
}
if (names != NULL)
free(names);
return 0;
}
This: 这个:
names = (char**)malloc(77 * sizeof(char));
is wrong, sizeof (char)
is 1 which is not what you want. 是错误的, sizeof (char)
为1,这不是您想要的。
It should be: 它应该是:
names = malloc(77 * sizeof *names);
This is the same as 77 * sizeof (char *)
since names
is char **
which makes the type of *names
be char *
. 这与77 * sizeof (char *)
相同,因为names
是char **
,这使得*names
的类型为char *
。
The cast is not necessary and should be omitted in my opinion. 强制转换不是必需的,我认为应该省略。
It's very strange (and an obvious code smell) to use a literal 77
instead of count
for the array length, of course. 当然,使用字面量77
代替数组长度count
是非常奇怪的(并且有明显的代码味道)。
You probably want names = (char**)malloc(counter * sizeof(char*));
您可能想要names = (char**)malloc(counter * sizeof(char*));
. 。
Also free
handles null pointers, no need to check the pointer for null before calling it. free
处理空指针,无需在调用前检查指针是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.