c - 更改数组中的A字符串时出现C分段错误
问题描述
我有这个指向字符串的指针数组,它在 Main 函数上方定义为 public:
char *Code[]={"MAIN: add r3, LIST",
"LOOP: prn #48",
"lea STR, r6",
"inc r6",
"mov r3, K",
"sub r1, r4",
"bne END",
"cmp val1, #-6",
"bne %END",
"dec K",
"jmp %LOOP",
"END: stop",
"STR: .string “abcd”",
"LIST: .data 6, -9",
".data -100",
".entry K",
"K: .data 31"};
我编写了一个函数,假设查找 A 行中是否有一系列制表符和空格,如果有,则应更改字符串,以便只有一个空格或制表符:
void SpaceTabRemover()//function to make sure there are no two tabs or spaces following eachother
{
int i,j=0,k=0; //i=which line we are at, j=which char of the line we ar at, k=placeholder for the last char which equal to space or tab
for(i=0;i<sizeof(Code)/sizeof(Code[0]);i++)
{
while(Code[i][j])
{
if ((Code[i][j]==' '||Code[i][j]=='\t')&&(Code[i][j+1]==' '||Code[i][j+1]=='\t'))//checks if there is a sequence of tabs and spaces
{
Code[j][k++]=Code[i][j];
}
j++;
}
Code[j][k]='\0';
}
}
我认为代码应该可以通过它的外观工作,除非我写错了并且我看不到它,
我的问题是当函数确实在 A 行中找到两个空格或制表符并尝试对字符串进行更改时,我收到了一个我以前从未见过的错误:
程序在 main.c.112 Code[j][k++]=Code[i][j] 处的 SpaceTabRemover() 中收到信号 SIGSEGV 分段错误
这个错误是什么意思,我该如何解决?
解决方案
arrya 的元素Code
是指向字符串文字的指针,不允许修改。
在修改字符串之前,您必须将字符串复制到可修改的缓冲区。
#include <stdlib.h> // for malloc() and exit()
#include <string.h> // for strlen() and strcpy()
void SpaceTabRemover()//function to make sure there are no two tabs or spaces following eachother
{
int i,j=0,k=0; //i=which line we are at, j=which char of the line we ar at, k=placeholder for the last char which equal to space or tab
for(i=0;i<sizeof(Code)/sizeof(Code[0]);i++)
{
// allocate buffer and copy strings
char* buffer = malloc(strlen(Code[i]) + 1); // +1 for terminating null-character
if (buffer == NULL) exit(1); // check if allocation succeeded
strcpy(buffer, Code[i]); // copy the string
Code[i] = buffer; // assign the copied string to the element of array
while(Code[i][j])
{
if ((Code[i][j]==' '||Code[i][j]=='\t')&&(Code[i][j+1]==' '||Code[i][j+1]=='\t'))//checks if there is a sequence of tabs and spaces
{
Code[j][k++]=Code[i][j];
}
j++;
}
Code[j][k]='\0';
}
}
推荐阅读
- python - 函数后跟(点)然后变量 [func.var] 在 python 中是什么意思?
- python-3.x - 使用解析器重新同步的 PLY.yacc 错误处理
- ios - 在显示之前将 ViewController 加载到 ContainerView 中,因此没有可见的过渡
- variables - 如何在 Lua 中获取表的实际副本?
- javascript - “获取”某些数据时重音问题
- virtualbox - 在 Manjaro(Arch Linux)上通过 AUR 构建 v8 失败 - 消息:“错误:check() 中发生故障”
- spring-boot - 扩展组件的服务的 Spring Boot 测试配置
- redux - 减速器:面向动作的减速器还是面向结构的减速器?
- javascript - 我怎样才能通过
在对象中的字符串中作为子组件的道具? - java - 在 SpringBoot 2.1.1.RELEASE 的 RestTemplate 中添加 HttpHeaders