c - 使用 strcpy 到 calloc'ed 位置时,大小为 1 的写入无效
问题描述
我正在尝试将给定的字符串解析为以 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 有问题,但我束手无策。我该如何解决这个问题?不知道我是如何得到这些错误的
编辑:发布完整代码,以便您可以重现错误
解决方案
NULL
就像@DavidRanieri 所说,由于我的索引不正确,问题源于我用 覆盖元素。所以我只是将这两行更改为:
commands[pipeCount+1][a] = NULL;
commands[pipeCount+1] = NULL;
现在,一切都按预期进行。
推荐阅读
- javafx - 任务不更新局部变量
- python - 为什么 gcloud ml-engine submit 命令给出“requested cpu s超过 quota”?
- c# - 在 C# 中将泛型显式转换为另一种类型
- html - 如何垂直对齐动态长度的文本,同时让它环绕浮动图像?
- python - 为什么 base64.b64encode 返回值 b'somestring' 而不是简单的 'somestring'?
- python - 如何在 Outlook (2010) 全局地址列表中搜索多个名称?
- angular - 角度字符串插值在 JSON 对象值上打印空字符串
- python - 需要有关 python 描述符功能的帮助
- android - Dart 项目可以拥有的最大方法数是多少?
- python - 在反向查询(related_name)中检索 Django QuerySet 匹配字段