[英]free(); and malloc(); keeps crashing (C)
我建立了這段代碼來練習指針,程序不斷崩潰。當我輸入一個大數字進行counter
時,它似乎崩潰了。 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
處理空指針,無需在調用前檢查指針是否為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.