您的位置:首页 > 编程语言 > C语言/C++

C语言sprintf使用出现段错误

2015-09-22 08:48 513 查看
#include <stdio.h>
#include <stdlib.h>

void Block(int function_no,int instrument_no)
{
<span style="white-space:pre">	</span>char *function;
char *instrument;
char *result;
sprintf(function,"%d",function_no);
sprintf(instrument,"%d",instrument_no);
sprintf(result,"%d.%d",function_no,instrument_no);
printf("%s\n",result);
}
int main()
{
Block(3,5);
}


c文件命名为a.c

使用GCC编译器进行编译:gcc a.c -o a.out生成a.out的可执行文件
执行该可执行文件:./a.out
出现以下错误:
a.out[14606]: segfault at 0 ip 0000003e1e689901 sp 00007fff0658cb48 error 6 in libc-2.12.so[3e1e600000+18a000]
</pre><pre name="code" class="html">问题原因:在申请char型指针的时候,如果只是声明指针,是没有分配存储空间的,所以在sprintf赋值的过程中就会出错,此时将上文代码中的红色部分设置成为char型数组,在声明的过程中就分配好内存,如:
<span style="white-space:pre">	</span>char function[10];

</pre><pre name="code" class="html">
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息