简体   繁体   English

使用C的字符串数组中的内存不足

[英]Out of Memory in String Arrays with C

I have a string array like this: 我有一个像这样的字符串数组:

char **strArray;

this array is full and i can print its contents by this method: 该数组已满,我可以通过以下方法打印其内容:

while(*strArray){
printf("%s\n",*(strArray++));
}

This works normally. 这正常工作。 But when i use this: 但是当我使用这个:

while(*strArray){
process(*(strArray++));
}

I take out of memory error on second string in array. 我取出数组第二个字符串的内存错误。 It runs for first string, but fails when goes for second. 它在第一个字符串上运行,但是在第二个字符串上失败。

Thanks for help! 感谢帮助!


Process method is like below: 处理方法如下:

process(char *line)
{
char *server_id,*delimiter,*outputMessage,*capacity_str;
int capacity;
delimiter = " ";
strtok(line,delimiter);
server_id = (char *)strtok(NULL,delimiter);
capacity_str = (char *)strtok(NULL,delimiter);
capacity = atoi(capacity_str);
curr_server = (server *)malloc(sizeof(server));
curr_server->server_id = server_id;
curr_server->capacity = capacity;
curr_server->full_capacity = 0;
curr_server->next = head_server;
head_server = curr_server;
strcpy(outputMessage , "server added ");
strcat(outputMessage,server_id);
strcat(outputMessage,"~");
strcat(outputMessage,capacity_str);
strcat(outputMessage,"\n");
writeOutput(outputMessage);
}

outputMessage needs to be allocated before you strcpy/strcat to it. 在对strcpy / strcat进行分配之前,需要先分配outputMessage。 I'm surprised you get an out of memory error and not just a segmentation fault. 我很惊讶您遇到内存不足错误,而不仅仅是分段错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM