c - 读取字符串时出错

标签 c string deque

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

//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");
}

最佳答案

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* 的地址,因此您可以只交换元素而不是复制其内容。

关于c - 读取字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12804450/

相关文章:

c - 如何检测xlib应用程序是否从xinit运行?

php - java.lang.String类型的值<br的错误无法转换为JSONObject

string - Lua-如何查找具有1个或2个字符差异的子字符串

python - open(logPath, 'r') as fh : 语法错误

c - 为什么 Visual Studio 2010 中的 ssize_t 被定义为无符号?

c - 用 C 语言枚举注册表项及其数据

c - 反转数组而不使用第二个数组。 (C语言)

c - 字符串修改函数 : return void or char*?

java - 使用循环数组实现双端队列?

algorithm - 优先级队列和双端队列