gpt4 book ai didi

c - 使用 strcpy 到 calloc 位置时大小为 1 的写入无效

转载 作者:太空宇宙 更新时间:2023-11-04 03:09:33 24 4
gpt4 key购买 nike

我正在尝试将给定的字符串解析为以 NULL 结尾的命令数组,因为我正在设计 C shell。所以我想要的命令结构是:

// Null terminated commands
char** command1 = {"ls", "-l", NULL};
char** command2 = {"wc", NULL};

// Final NULL terminated array of commands
char*** cmd = {command1, command2, NULL};

我的代码是:

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

int main()
{
int lastPipe = 0; // To track the last position of the "|" symbol
int pipeCount = 0; // Count of the pipes

char*** commands = (char***) calloc (10, sizeof(char**));
for (int i=0; i<10; i++)
{
commands[i] = (char**) calloc (10, sizeof(char*));
for (int j=0; j<10; j++)
{
commands[i][j] = (char*) calloc (10, sizeof(char));
}
}

int a = 0;

char* argVector[] = {"ls", "|", "wc", NULL};

// argVector is the parsed version of the input string
// For instance, argVector = {"ls", "|", "wc", NULL};
for (int i=0; argVector[i] != NULL; i++)
{
if (strcmp(argVector[i], "|") == 0)
{
if (lastPipe == 0)
{
for (a=0; a<i; a++)
strcpy(commands[pipeCount][a], argVector[a]);

// Make NULL terminated command
commands[pipeCount][a] = NULL;

// Update Pipe location
lastPipe = i;
pipeCount++;
}

else
{
for (a = lastPipe+1; a<i; a++)
{
strcpy(commands[pipeCount][a-lastPipe-1], argVector[a]);
}

// Make NULL terminated command
commands[pipeCount][a-lastPipe-1] = NULL;

// Update Pipe location
lastPipe = i;
pipeCount++;
}

}

if (pipeCount > 0)
{
for(a=lastPipe + 1; a<=i; a++)
{
if (strcmp(argVector[a], "|") != 0)
// This line gives the Segmentation Fault
strcpy(commands[pipeCount][a-lastPipe-1], argVector[a]);
}
commands[pipeCount][a-lastPipe-1] = NULL;
}

}

// Now, I must have a NULL terminated array of Commands
commands[pipeCount][a] = NULL;
commands[pipeCount] = NULL;

// Print the commands
for (int i=0; commands[i]!=NULL; i++)
{
for(int j=0; commands[i][j]!=NULL; j++)
{
printf("Commands[%d][%d] = %s\n", i, j, commands[i][j]);
}
}
}

当我运行它时,出现段错误,当我查看 valgrind 时,它向我显示:

==12458== Invalid write of size 1
==12458== at 0x483BDC8: strcpy (vg_replace_strmem.c:512)
==12458== by 0x109E4B: main (pipe.c:251)
==12458== Address 0x0 is not stack'd, malloc'd or (recently) free'd

显然,最后一个 strcpy 有问题,但我束手无策。我该如何解决这个问题?不确定我是如何得到这些错误的

编辑:发布完整代码以便您可以重现错误

最佳答案

正如@DavidRanieri 所说,问题源于我用 NULL 覆盖元素,因为我的索引不正确。所以我只是将这两行更改为:

    commands[pipeCount+1][a] = NULL;
commands[pipeCount+1] = NULL;

现在,一切都按预期进行。

关于c - 使用 strcpy 到 calloc 位置时大小为 1 的写入无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57901405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com