简体   繁体   English

c中的char数组的分割错误

[英]segmentation fault with char array in c

please tell me why this code give me segmentation fault? 请告诉我为什么这段代码给我分段错误?
I want to split the command into tokens but I don't know why it give me segmentation fault!! 我想将命令拆分为令牌,但我不知道为什么它会给我分段错误!

char command[500]="asdadas asdasdas asdadas";   
int i,j,k;
char tokens[4][200];

for(i=0,j=0,k=0;  i<strlen(command);  i++)
{
    if(command[i]==' ') 
    {
        tokens[j][k]='\0';
        k=0;
        j++;
        continue;
    }

    tokens[j][k]=command[i];
    k++;
}
tokens[j][k]='\0';

command is uninitialised. command未初始化。 That means that the strlen(command) call might run beyond the 500 bytes, causing a segmentation fault. 这意味着strlen(command)调用可能会超出500字节,从而导致分段错误。

Initialise your command array before using it. 在使用之前初始化command数组。 For example with memset . 例如与memset

Other than that, there is no bounds checking whatsoever and some arbitrary array lengths. 除此之外,没有边界检查任何东西和一些任意的数组长度。 This is bound to fail. 这注定会失败。

You have a problem with tokens . 您对tokenstokens You are incrementing j and k in each iteration without any check. 您将在每次迭代中递增jk而不进行任何检查。

Anyway, dou you know there already exists functions that do what you wanna do? 无论如何,您知道已经存在执行您想执行的功能的功能吗?

To add More into other folks answer, you can use strsep. 要将“更多”添加到其他人的答案中,可以使用strsep。 Look at the following sample code: 看下面的示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main ()
{
char * command=NULL, *tok=NULL;

command =strdup("asdadas asdasdas asdadas");
while ((tok = strsep(&command, " ")) != NULL )
{
  printf ("..%s..\n", tok);
}

Hope it helps. 希望能帮助到你。 ;) ;)

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

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