我试图在C中编写一个简短的程序,它从stdin中取出空格分隔的标记,shuffles(permutes)标记,然后将shuffles标记打印到stdout。我的改组算法运行正常,问题在于令牌解析。我想将令牌存储在动态字符串数组中,以便程序可以支持通过stdin传入任意数量的令牌。但是,每当需要扩展阵列时,我当前对动态数组的实现会导致分段错误。我做错了什么?
我的代码:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 33
int main(int argc, char* argv[]) {
int i,j,k;
i=j=k=0;
int arrSize = 10;
/* Temp fix */
/* Get token count as command line argument */
//if (argc==2) { sscanf(argv[1],"%d",&arrSize); }
char c='\0';
char* t;
char** datArr = (char**)malloc(sizeof(char*)*arrSize);
//char* datArr[arrSize];
char token[BUFFERSIZE];
while ( (c=getc(stdin)) != EOF && c != '\0') {
if(isspace(c)) {
token[i] = '\0';
i=0;
if ( j >= arrSize) {
arrSize *= 2;
realloc(datArr, arrSize);
}
char* s = (char*)malloc(sizeof(char[BUFFERSIZE]));
strcpy(s,token);
datArr[j++] = s;
}
else if(i+1 < BUFFERSIZE) {
token[i++] = c;
}
}
/* Permutate & Print */
srand(time(NULL));
for(i=0;i<j;++i) {
k = rand()%(j-i);
t = datArr[k];
datArr[k] = datArr[j-i-1];
datArr[j-i-1] = t;
}
for(i=0;i<j;++i) { printf("%s ",datArr[i]); }
printf("\n");
return 0;
}
注意:我知道我确实释放了内存
一些样本输入(以卡片为主题):
2C 3C 4C 5C 6C 7C 8C 9C 10C JC KC QC AC 2S 3S 4S 5S 6S 7S 8S 9S 10S JS KS QS AS
答案 0 :(得分:0)
您是否尝试过测试:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 33
int main(int argc, char* argv[]) {
int i,j,k;
i=j=k=0;
int arrSize = 10;
/* Temp fix */
/* Get token count as command line argument */
//if (argc==2) { sscanf(argv[1],"%d",&arrSize); }
char c='\0';
char* t;
char** datArr = (char**)malloc(sizeof(char*)*arrSize);
//char* datArr[arrSize];
char token[BUFFERSIZE];
while ( (c=getc(stdin)) != EOF && c != '\0') {
// Just read the file
}
}
我认为这是一个无限循环。
getc()返回一个int,而不是一个char,所以它应该永远不会停止读取文件,这是一个无限循环。这将耗尽内存,并最终保证seg故障。
我建议将char c='\0';
更改为int c;
并应用内存处理方面的改进。
答案 1 :(得分:0)
VaughnCato对原始OP的评论是对这个问题的正确答案。
“您需要使用datArr = (char**)realloc(datArr,arrSize*sizeof(char*));
”
感谢VaughnCato!