【发布时间】:2013-12-02 22:37:47
【问题描述】:
我在 ** 所包含的行上遇到了分段错误。 我通过管道输出: |状态:正常| |版本:0.85| |作者:普布鲁克斯| |项目:0|
在下面的代码中,当我在 printf 语句中打印出 '\n' 后,它给了我一个分段错误。我不知道如何调试这个.. 有人有线索吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char string[300];
struct NameValue {
char *name;
char *value;
};
struct NameValue *pairs;
void ReadStdin(int argc, char *argv) {
int x;
fread(string, sizeof (char), 300, stdin);
printf("%s\n", string);
}
void ParseInput() {
int x, num = 0; //figure out how many i need
for (x = 0; x < 300; x++) {
if (string[x] == '|') {
num++;
}
}
num /= 2; //num = how many i need
pairs = (malloc(num)); //allocate the array
int pipe = 0, i, j = 0, tempCounter = 0;
char tempName[50], tempValue[50];
printf("%lu \n", sizeof (string) / sizeof (string[0]));
if (pairs != 0) {
for (i = 0; i <= num; i++) { //counts pairs
printf("i = %i\n", i);
printf("j = %i, pipe: %i \n", j, pipe);
if (string[j] == '|') {
printf("there's a pipe\n");
pipe++;
j++;
}
while (string[j] != ':') {
printf("counter for main string: %i\n tempCounter: %i\n", j, tempCounter);
tempName[tempCounter] = string[j];
tempCounter++;
j++;
if (string[j] == ':') {
tempName[tempCounter] = '\0';
tempCounter = 0;
**printf("~~~~tempName\n is: %s", tempName);**
break;
}
}
while (string[j] != '|') {
j++;
tempValue[tempCounter] = string[j];
tempCounter++;
if (string[j] == '|') {
tempValue[tempCounter] = '\0';
tempCounter = 0;
strcpy(pairs[i].value, tempValue);
pipe++;
break;
}
}
}
}
}
int main(int argc, char *argv) {
ReadStdin(argc, argv);
ParseInput();
return (EXIT_SUCCESS);
}
编辑:对不起!我意外删除了空终止字符行。它在那里,但它仍然给我错误。
编辑:更多信息:在程序吐出分段错误之前,j 变量递增到 6,临时计数器递增到 5。
【问题讨论】:
-
pairs = (malloc(num)); //allocate the array什么是对? -
Pairs 是指向具有 char* 名称和值的结构的指针。然后我使用 malloc 使它指向一个数组(我的措辞可能不正确,但我希望你明白)
-
我明白了:它是一个全局指针。但是
pairs = (malloc(num)); //allocate the array,你不打算:pairs = malloc(num * sizeof *pairs);? -
我想为其他程序的输出分配足够的对。在这种情况下,我得到 4 行文本,所以我做了 malloc'd 4 对。
-
错误:你 malloc()d 四个字符。请记住: malloc() 以字符计。 Malloc不知道你想要什么。它只计算字符。幸运的是,sizeof 也按字符计算。
标签: c segmentation-fault coredump