【问题标题】:ERROR READING STRING错误读取字符串
【发布时间】:2012-09-30 01:05:03
【问题描述】:

我的代码不起作用。在我接受字符串时出现运行时错误。这段代码有什么问题?

//this is what i have in main()
char *ele,*s[max];
int *count,temp=0;
count=&temp;   
printf("Enter string to insert: ");
scanf("%s",ele);
addleft(s,ele,count);

//following is the function definition
void addleft(char *s[max],char *ele,int *count)
{
    int i;
    if((*count)==max)
    {
        printf("Queue full!\n");
        return;
    }
    for(i=*count;i>0;i--)
        strcpy(s[i],s[i-1]);
    strcpy(s[0],ele);
    (*count)++;
    printf("String inserted at left!\n");
}

【问题讨论】:

  • 我会将标题更改为“错误的代码实现导致错误的输入字符串处理”。标题听起来像是您将输入字符串归咎于代码错误。 ;-)
  • 对不起,我没注意标题。此时对我来说更重要的是我必须提交这个 tom 的代码:)

标签: c string deque


【解决方案1】:

ele 是一个未初始化的char* 并且没有与之关联的内存,scanf() 将尝试写入它导致未定义的行为,可能是分段错误。

您需要为ele动态分配内存或声明一个本地数组并防止在使用scanf()时缓冲区溢出:

char ele[1024];
if (1 == scanf("%1023s", ele))
{
    /* Process 'ele'. */
}

此外,函数addleft()s 上使用strcpy(),它是char* 的数组,并且数组中的每个char* 都被统一化。这是未定义的行为和可能的分段错误。要更正,您可以使用strdup(),否则malloc()strcpy()

/* Instead of:
       strcpy(s[0],ele);
   use:
 */
s[0] = strdup(ele);

请注意,addleft() 函数内的 for 循环很危险,因为 s 中包含的 char* 不一定具有相同的长度。这很容易导致超出数组末尾的写入。但是,由于元素是动态分配的 char* 的地址,您可以只交换元素而不是复制它们的内容。

【讨论】:

    【解决方案2】:

    您正在导致缓冲区溢出,因为指针 ele 未指向任何已分配的内存。您正在写入程序需要运行的内存,因此使其崩溃。我建议您像这样在您的程序中实现malloc

    char *ele;
    if (!(ele = malloc(50))) //allocate 50 bytes of memory 
    {
        //allocation failed
        exit(0);
    }
    scanf("%s", ele); //string can hold 50 bytes now
    free(ele);        //free allocated space
    

    您可能想阅读malloc 函数here

    更简单的方法是将ele 设为数组而不是指针:

    char ele[50]; //ele is an array of 50 bytes 
    

    【讨论】:

      【解决方案3】:

      sscanf("%s", ele) 将输入放入 'ele' 指向的内存中。但是'ele'从未被初始化为指向任何东西。比如:

      char ele[128];
      

      char* ele = malloc(...)
      

      应该修复它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-12
        • 1970-01-01
        • 2015-04-07
        • 2018-04-09
        相关资源
        最近更新 更多