【发布时间】:2017-05-11 10:02:14
【问题描述】:
如何保持分配内存的位置,以便释放排序数组的内存不会受到影响?
我正在尝试对指针数组进行排序。我注意到当我释放 words 双指针变量时,它会给出错误 HEAP CORRUPTION DETECTED。我输入的输入是“f ff 1”。
未排序:f ff 1 排序:1 f ff
我注意到,当我对它进行排序和释放时,它会期望相同的顺序,即“f ff 1”。这就是为什么我得到了一些错误。
关于如何释放已排序指针数组的任何建议?
#include <stdio.h>
/*
A logical type
*/
typedef enum {
false,
true,
} bool;
/*
Bubble Sort
*/
void sort(char *myargv[], int n)
{
int i, j, cmp;
char tmp[256];
if (n <= 1)
return; // Already sorted
for (i = 0; i < n; i++)
{
for (j = 0; j < n-1; j++)
{
cmp = strcmp(myargv[j], myargv[j+1]);
if (cmp > 0)
{
strcpy(tmp, myargv[j+1]);
strcpy(myargv[j+1], myargv[j]);
strcpy(myargv[j], tmp);
}
}
}
}
void printArray(char *myargv[], int myargc)
{
int i = 0;
for (i = 0; i < myargc; ++i) {
printf("myargc[%d]: %s\n",i , myargv[i]);
}
}
int main (int argc, char *argv[])
{
char text[256];
char *myargv[256];
char *myargvTemp[256];
int myargc;
int i = 0;
int text_len;
bool new_word = false;
int index_start_word = 0;
char **words; //this will store the found word
int count = 0;
while(1){
printf( "Enter text:\n");
gets(text); //get the input
text_len = strlen(text); //get the length of the text
words = (char **) malloc(text_len * sizeof(char));
if (strlen(text) == 0 || text == '\0') exit(0); //exit if text is empty
for (i = 0; i < text_len ; ++i){
if(text[i] != ' '){ //if not space
if(new_word == false){
new_word = true;
index_start_word = i;
}
} else {
if (new_word == true) {
words[count] = (char *)malloc(i - index_start_word * sizeof(char)+1); //memory allocation
strncpy(words[count], text + index_start_word, i - index_start_word);
words[count][i - index_start_word] = '\0'; //place NULL after the word so no garbage
myargv[count] = words[count];
new_word = false;
count++;
}
}
if (new_word == true && i == text_len-1){
words[count] = (char *)malloc(i - index_start_word * sizeof(char)+2);
strncpy(words[count], text + index_start_word, (i+1) - index_start_word);
words[count][(i+1) - index_start_word] = '\0';
myargv[count] = words[count];
new_word = false;
count++;
}
}
myargc = count;
//not sorted
printf("myargc is: %d\n", myargc);
printArray(myargv, myargc);
//sorting happen
sort(&myargv, myargc);
printf("-----sorted-----\n");
printf("myargc is: %d\n", myargc);
printArray(myargv, myargc);
memset(myargv, 0, 255);
count = 0;
i = 0;
//free the memory of words
for (i=0; i<myargc; ++i) {
free(words[i]);
}
}
return 0;
}
【问题讨论】:
-
添加
#include <string.h>和#include <stdlib.h>,打开编译器警告并阅读它们。 -
我明白你的意思,我想它应该是 sort(myargv, myargc); .但是通过改变释放错误仍然存在。
-
可能你没有为
malloc分配足够的内存。检查您的写入内容是否超出了 malloc 返回的内存块。 -
试试
words = (char **) malloc(text_len * sizeof(char *)) -
这是我见过的最奇怪的定义
bool的方式。如果你可以使用C99或以上,你应该使用<stdbool.h>。
标签: c arrays pointers memory-management