69,379
社区成员
发帖
与我相关
我的任务
分享
//使用动态分配
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int i,L;
char *p;
void main() {
for (i=0;i<20000;i++) {
L=rand();
p=malloc(L);
if (NULL==p) {
printf("malloc error!\n");
continue;
}
memset(p,0,L);
free(p);
}
}
//不使用动态分配
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define MAXLEN 30000
int i,L;
char buf[MAXLEN];
char *p;
void main() {
p=&buf[0];
for (i=0;i<20000;i++) {
L=rand();
if (L>MAXLEN) {
printf("L>MAXLEN==%d, ignore spilth.\n",MAXLEN);
L=MAXLEN;
}
memset(p,0,L);
}
}
typedef struct {
char ** command;
int length;
}
command_split_data;
void str_split(const char * src, const char * grep,command_split_data * ret) {
int src_len = strlen(src);
assert(src_len<1000);
char src_temp[src_len];
strcpy(src_temp, src);
int i;
char * p;
ret->command =(char **)malloc(100*sizeof(char *));
assert(ret->command);
printf("set\n");
p = strtok(src_temp, grep);
assert(p);
ret->command[0] = (char *)malloc(strlen(p)+1);
strcpy(ret->command[0],p);
printf("command %d : %s\n", 0, ret->command[0]);
printf("set end\n");
i = 1;
while (p = strtok(NULL, grep)) {
ret->command[i] = (char *)malloc(strlen(p)+1);
strcpy(ret->command[i],p);
printf("command %d : %s\n", i, ret->command[i]);
i++;
if (i>=100) {
printf("up to 100 commands!\n");
break;
}
}
printf("return\n");
ret->length = i;
}
#include <iostream>
#include <stdio.h>
#include <string.h>
const int SIZE = 1024 * 8;
char APPBUF[SIZE]; // 设置缓冲区 APPBUF
// 本函数完成从 分词里找最长的分词,使用缓冲区,避免了内存泄漏
char* search(const char* chbuf , const char* val);
int main()
{
const char* str = "我/爱/中珅/||我/爱珅/中文/||我爱1234567890/中/文/||我爱/中文/分/||我爱/中文/分词/";
char* pch = search(str , "|");
printf("%s\n", pch);
printf("%s\n", search("http://topic.csdn.net/u/20110822/20/e369cc10-5392-4763-b2cd-da4995b2cafb.html" , "/"));
printf("%s.png\n", search("http://hi.csdn.net/attachment/201108/22/3362235_1313993745S1YP.png" , "/."));
return 0;
}
char* search(const char* chbuf , const char* val)
{
char* ret = APPBUF; // 使用缓冲区,先清0
memset(ret, 0, SIZE);
char* pch = NULL;
char* funbuf = new char[strlen(chbuf) + 1];
strcpy(funbuf, chbuf);
pch = strtok(funbuf, val);
while (pch != NULL) {
if (strlen(ret) < strlen(pch)) { // 获取最长的字符串单元
strcpy(ret, pch);
}
pch = strtok(NULL, val);
}
delete[] funbuf;
return ret;
}