自由();和 malloc();不断崩溃(C)
free(); and malloc(); keeps crashing (C)
我编写这段代码是为了练习指针,当我向 counter
输入一个大数字时,程序保持 crashing.it 似乎崩溃了。 1-5 显然不会影响它,但是当您输入 30 时它会不断崩溃,有时是在分配本身 malloc(...
上,有时是在 free(names[i]);
函数中。
这里有什么问题?
#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;
}
这个:
names = (char**)malloc(77 * sizeof(char));
是错误的,sizeof (char)
是1,这不是你想要的。
应该是:
names = malloc(77 * sizeof *names);
这与 77 * sizeof (char *)
相同,因为 names
是 char **
,这使得 *names
的类型为 char *
。
演员表不是必需的,我认为应该省略。
当然,对于数组长度使用文字 77
而不是 count
非常奇怪(并且有明显的代码味道)。
你可能想要 names = (char**)malloc(counter * sizeof(char*));
.
还free
处理空指针,调用前无需检查指针是否为空。
我编写这段代码是为了练习指针,当我向 counter
输入一个大数字时,程序保持 crashing.it 似乎崩溃了。 1-5 显然不会影响它,但是当您输入 30 时它会不断崩溃,有时是在分配本身 malloc(...
上,有时是在 free(names[i]);
函数中。
这里有什么问题?
#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;
}
这个:
names = (char**)malloc(77 * sizeof(char));
是错误的,sizeof (char)
是1,这不是你想要的。
应该是:
names = malloc(77 * sizeof *names);
这与 77 * sizeof (char *)
相同,因为 names
是 char **
,这使得 *names
的类型为 char *
。
演员表不是必需的,我认为应该省略。
当然,对于数组长度使用文字 77
而不是 count
非常奇怪(并且有明显的代码味道)。
你可能想要 names = (char**)malloc(counter * sizeof(char*));
.
还free
处理空指针,调用前无需检查指针是否为空。