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">
相关文章推荐
- 在Windows平台下使用安装GCC(图)
- linux使用gcc编译c语言共享库步骤
- 基于C语言中段错误的问题详解
- C/C++编译器GCC下的常用编译命令总结
- GCC 编译c程序的方法及过程解析
- Glusterfs的编译选项 #pragma GCC poison system popen
- 【笔记】CentOS上源码安装GCC 4.8.2
- 【笔记】CentOS
- RHEL 4.7 (64bit) 环境安装 GCC 4.6 测试记录 (更新至gcc-4.6.1)
- GCC 5 即将发布
- [转载]Visual Studio, GCC, Clang, Intel 对 C++11 特性的支持一览表
- C++爱好者博客
- gcc工具的运用
- gdb的运用
- GCC内联汇编(1)Get started
- GCC内嵌汇编
- g++编译 参数 .
- RHEL5.3 gcc rpm包安装
- linux GCC 64位编程技巧
- linux gcc 区分32位或64位编译