- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在将字符串从命令行上的输入字符串复制到二维数组中的字符串时遇到问题。我的程序必须将由字母组成的字符串与任何非字母字符分开。例如 hello23ght.!good 需要放入二维数组中:
我已经找到了最长的字符串和字符串的数量,以便我可以为我的二维数组分配内存,如下所示。
char **stringArr; //array to hold seperated strings
stringArr = (char **)malloc(numOfStrings * sizeof(char*)); //malloc rows of 2d array
if(stringArr == NULL) { //checks to see if memory was allocated correctly
return 1;
}
int y;
for (y = 0; y < numOfStrings; y++) { //malloc columns of array
stringArr[y] = (char*) malloc((longestString + 1) * sizeof(char));
if(stringArr[y] == NULL) { //checks to see if memory was allocted correctly
return 1;
}
}
后记我编写了这段代码来查找输入字符串中的各个字母字符串,并将每个字母字符串放入二维数组的一个“槽”中:
while (argv[1][a] != '\0') { // Keep traversing the argument until the null char is reached
if (isAlpha(argv[1][a]) == 1) { // if the first char in argv[1] is a letter, copy it into the first row and first column of stringArr
stringArr[b][c] = argv[1][a];
printf("%c" , stringArr[b][c]); //test
a++;
c++;
//printf("%d %d \n", a, c);
} else if (a > 0 && isAlpha(argv[1][a]) != 1 && isAlpha(argv[1][a-1]) == 0) { //If the previous character is a letter and the current character isn't a letter increment a and b. (We have hit the end of the first unique string)
a++;
stringArr[b][c+1] = '\0'; //Setting the null byte for the unique string
b++; //incrementing b to the next unique string
printf("%d %d %d \n", a, b, c);
c = 0; // resetting c for the next unique string
} else {// if neither of the first two statments occur only increment var a since we have hit a repeating separating character.
a++;
}
}
但是,当我运行代码时,出现以下错误:
==46957==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000ef37 at pc 0x000103a76b8c bp 0x7fff5c18a910 sp 0x7fff5c18a908
WRITE of size 1 at 0x60200000ef37 thread T0
SUMMARY: AddressSanitizer: heap-buffer-overflow ??:0 main
Shadow bytes around the buggy address:
0x1c0400001d90: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001da0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001db0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001dc0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001dd0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa 07 fa
=>0x1c0400001de0: fa fa 07 fa fa fa[07]fa fa fa 00 06 fa fa 00 00
0x1c0400001df0: fa fa 00 04 fa fa 00 06 fa fa fd fd fa fa fd fd
0x1c0400001e00: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001e10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001e20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x1c0400001e30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
==46957==ABORTING
hlowrdjAbort trap: 6
我不确定到底出了什么问题,但我假设要么我没有为二维数组分配足够的内存,要么我的 while 语句没有准确地从输入字符串中复制唯一的字母字符串。
编辑我忘了添加这个,但 a、b 和 c 确实初始化为 0。
编辑2以下是如何检索 numOfStrings 和longestString
int j;
int numOfStrings=0, longestString=0, x=0;
//numOfStrings indicates total separated strings, longestString is the longest seperated string, x is the current length of the string
for (j = 0; argv[1][j] != '\0'; j++) { // Traversing through the input string
if (isAlpha(argv[1][j])) { //If the current char is a letter x is incremented by 1
x++;
} else if (!isAlpha(argv[1][j]) && isAlpha(argv[1][j-1])) { //If the current char is not a letter and the previous char is a letter then increment numberOfStrings by 1
numOfStrings++;
if (x > longestString) { //Since we hit a non letter char, if the x val is greater than the current longest string, replace longestString with x.
longestString = x;
}
x = 0;
}
}
if(isAlpha(argv[1][j - 1])) { //Checks the last character if it is a letter and then accounts for the string associated with that letter.
numOfStrings++;
if(x > longestString) { // If the last string is a the largest string then this will store its length in longestString
longestString = x;
}
}
编辑3我的 isAlpha 函数
int isAlpha (char a){
if ((65 <= a && a <= 90) || (97 <= a && a <= 122) ) {
return 1;
}
return 0;
} //Determines if a char is a letter or not using ASCII values. Returns 1 if true otherwise returns 0.
最佳答案
不知道如何计算numOfStrings
和longestString
,以及知道如何初始化运行索引 a
、b
、c
后,很难知道错误在哪里:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char **stringArr;
// emulating your allocation
stringArr = calloc(5, sizeof(char*));
stringArr[0] = calloc(1, 100);
stringArr[1] = calloc(1, 100);
stringArr[2] = calloc(1, 100);
stringArr[3] = calloc(1, 100);
stringArr[4] = calloc(1, 100);
if(argc != 2)
{
fprintf(stderr, "usage: %s arg\n", argv[0]);
return 1;
}
int i = 0; // index for scanning argv
int j = 0; // index of current stringArg buffer
int k = 0; // index of (end of) string in stringArg[j]
// state 0: alpha mode
// state 1: non-alpha mode
int state = 0;
char c;
while((c = argv[1][i++]))
{
if(isalpha(c))
{
if(state)
{
// previous character was a non-alpha
// change state and reset indices
state = 0;
k = 0;
j++;
}
stringArr[j][k] = c;
stringArr[j][++k] = 0;
continue;
}
// not alpha, ignoring
state = 1;
// if line starts with non-alpha
if(j == 0 && i == 1)
j--;
}
for(i = 0; stringArr[i][0]; ++i)
puts(stringArr[i]);
free(stringArr[0]);
free(stringArr[1]);
free(stringArr[2]);
free(stringArr[3]);
free(stringArr[4]);
free(stringArr);
return 0;
}
我决定将扫描状态存储在变量中。这使得较小的 if
条件,更容易阅读。我的版本也可以处理这种情况当该行以非字母字符开头时。
输出为:
$ valgrind ./a 'hello23ght.!good'
==20478== Memcheck, a memory error detector
==20478== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==20478== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==20478== Command: ./a hello23ght.!good
==20478==
hello
ght
good
==20478==
==20478== HEAP SUMMARY:
==20478== in use at exit: 0 bytes in 0 blocks
==20478== total heap usage: 7 allocs, 7 frees, 1,564 bytes allocated
==20478==
==20478== All heap blocks were freed -- no leaks are possible
==20478==
==20478== For counts of detected and suppressed errors, rerun with: -v
==20478== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
编辑
我认为我的猜测是正确的,您的运行索引的初始化a
,b
和 c
或计算 numOfStrings
和 longestString
的方式可能是问题所在。我认为您计算 numOfStrings
和 longestString
的方式可能是错误的。但如果没有代码,就很难判断。
我在程序中用你的循环替换了我的 while
循环,我删除了 printf
在此之前,我将运行索引 a
、b
、c
初始化为 0。我没有改变内存分配的模拟,所以我知道有该示例有足够的空间。
这是您的代码的结果:
$ valgrind ./a-ops-version 'hello23ght.!good'
==20877== Memcheck, a memory error detector
==20877== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==20877== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==20877== Command: ./a hello23ght.!good
==20877==
hello
ght
good
==20877==
==20877== HEAP SUMMARY:
==20877== in use at exit: 0 bytes in 0 blocks
==20877== total heap usage: 7 allocs, 7 frees, 1,564 bytes allocated
==20877==
==20877== All heap blocks were freed -- no leaks are possible
==20877==
==20877== For counts of detected and suppressed errors, rerun with: -v
==20877== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
编辑2
我在您的代码中发现了错误:
stringArr[b][c+1] = '\0';
当 b
索引最长字符串时,这会导致错误。当这条线是执行后,这意味着当前字符不是字母字符,所以在在上一个循环中,您已经将 c
增加了 1。这就是为什么当你阅读时非 alpha,c
已经是 '\0'
终止字节的索引,因此对于您超出范围写入的最长字符串。
为了说明这一点
'?'
是未初始化的字符
input: hello23ght.!good
Up until b == 0, a == 4, c == 4
hello23ght.!good
^
|
a
c
|
v
0 1 2 3 4 5
+---+---+---+---+---+---+
stringArr[b]: | h | e | l | l | o | ? |
+---+---+---+---+---+---+
这是结果
if (isAlpha(argv[1][a]) == 1) {
stringArr[b][c] = argv[1][a];
那你就这样做
a++;
c++;
因此,a
更新为 5,并读取下一个字符:
input: hello23ght.!good
Up until b == 0, a == 5, c == 5
hello23ght.!good
^
|
a
c
|
v
0 1 2 3 4 5
+---+---+---+---+---+---+
stringArr[b]: | h | e | l | l | o | ? |
+---+---+---+---+---+---+
因为 '2'
是非 alpha,所以执行 else
block
} else {
a++;
}
再次增加a
,现在是 6。
循环继续,else if
被评估为 true,因为最后一个字符也是非 Alpha:
stringArr[b][c+1] = '\0';
已执行,但你的写入超出了限制,因为numOfStrings
是 5:
input: hello23ght.!good
Up until b == 0, a == 6, c == 5
hello23ght.!good
^
|
a
c c+1
| |
v v
0 1 2 3 4 5 6
+---+---+---+---+---+---+
stringArr[b]: | h | e | l | l | o | ? | beyond the bounds
+---+---+---+---+---+---+
yields:
==22229== Invalid write of size 1
==22229== at 0x108C0E: main (a.c:93)
==22229== Address 0x51e64e6 is 0 bytes after a block of size 6 alloc'd
==22229== at 0x4C2CF05: calloc (vg_replace_malloc.c:711)
==22229== by 0x108A4B: main (a.c:62)
==22229==
要修复此问题,您必须删除 +1
:
stringArr[b][c] = '\0';
请注意,当且仅当非 Alpha 出现时,您的算法才会起作用对,你有这个输入hello234ght.!good
,那么你将编程由于第一个else if
而崩溃,您将增加b
,最终您超出了双指针的范围。
看看我的版本,在我的版本中,您可以拥有尽可能多的非阿尔法喜欢。
我鼓励您学习和使用调试器。此类错误很容易出现单步执行循环时的位置,因为使用调试器您可以看到这些值每一步的所有索引。
最后一个较小的批评:
在你的 isAlpha
中你有:
if ((65 <= a && a <= 90) || (97 <= a && a <= 122) )
这并没有错,但我认为这样做是一种不好的做法,数字看起来像神奇的数字,比如你是从哪里想出这个数字的?我知道这些是 a-z 和 A-Z 的 ASCII 代码。
这是一个更好的做法
if (('A' <= a && a <= 'Z') || ('a' <= a && a <= 'z') )
关于arrays - 发生堆缓冲区溢出不确定是否在 C 中正确为二维数组分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470986/
#include using namespace std; class C{ private: int value; public: C(){ value = 0;
这个问题已经有答案了: What is the difference between char a[] = ?string?; and char *p = ?string?;? (8 个回答) 已关闭
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 此帖子已于 8 个月
除了调试之外,是否有任何针对 c、c++ 或 c# 的测试工具,其工作原理类似于将独立函数复制粘贴到某个文本框,然后在其他文本框中输入参数? 最佳答案 也许您会考虑单元测试。我推荐你谷歌测试和谷歌模拟
我想在第二台显示器中移动一个窗口 (HWND)。问题是我尝试了很多方法,例如将分辨率加倍或输入负值,但它永远无法将窗口放在我的第二台显示器上。 关于如何在 C/C++/c# 中执行此操作的任何线索 最
我正在寻找 C/C++/C## 中不同类型 DES 的现有实现。我的运行平台是Windows XP/Vista/7。 我正在尝试编写一个 C# 程序,它将使用 DES 算法进行加密和解密。我需要一些实
很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visit the help center . 关闭 1
有没有办法强制将另一个 窗口置于顶部? 不是应用程序的窗口,而是另一个已经在系统上运行的窗口。 (Windows, C/C++/C#) 最佳答案 SetWindowPos(that_window_ha
假设您可以在 C/C++ 或 Csharp 之间做出选择,并且您打算在 Windows 和 Linux 服务器上运行同一服务器的多个实例,那么构建套接字服务器应用程序的最明智选择是什么? 最佳答案 如
你们能告诉我它们之间的区别吗? 顺便问一下,有什么叫C++库或C库的吗? 最佳答案 C++ 标准库 和 C 标准库 是 C++ 和 C 标准定义的库,提供给 C++ 和 C 程序使用。那是那些词的共同
下面的测试代码,我将输出信息放在注释中。我使用的是 gcc 4.8.5 和 Centos 7.2。 #include #include class C { public:
很难说出这里问的是什么。这个问题是含糊的、模糊的、不完整的、过于宽泛的或修辞性的,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开它,visit the help center 。 已关
我的客户将使用名为 annoucement 的结构/类与客户通信。我想我会用 C++ 编写服务器。会有很多不同的类继承annoucement。我的问题是通过网络将这些类发送给客户端 我想也许我应该使用
我在 C# 中有以下函数: public Matrix ConcatDescriptors(IList> descriptors) { int cols = descriptors[0].Co
我有一个项目要编写一个函数来对某些数据执行某些操作。我可以用 C/C++ 编写代码,但我不想与雇主共享该函数的代码。相反,我只想让他有权在他自己的代码中调用该函数。是否可以?我想到了这两种方法 - 在
我使用的是编写糟糕的第 3 方 (C/C++) Api。我从托管代码(C++/CLI)中使用它。有时会出现“访问冲突错误”。这使整个应用程序崩溃。我知道我无法处理这些错误[如果指针访问非法内存位置等,
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 7 年前。
已关闭。此问题不符合Stack Overflow guidelines 。目前不接受答案。 要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于 Stack Overflow 来说是偏离主题的,因为
我有一些 C 代码,将使用 P/Invoke 从 C# 调用。我正在尝试为这个 C 函数定义一个 C# 等效项。 SomeData* DoSomething(); struct SomeData {
这个问题已经有答案了: Why are these constructs using pre and post-increment undefined behavior? (14 个回答) 已关闭 6
我是一名优秀的程序员,十分优秀!