分段错误(核心转储)错误访问动态数组中的元素
segmentation fault (Core dumped) error Access elements in dynamic array
我想从用户打印出来的字符串中获取它,并访问它的第一个字符,但是使用下面的代码我得到
segmentation fault (Core dumped)
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define GROW_BY 10
int main(){
char *str_p, *next_p, *tmp_p;
int ch, need, chars_read = 0;
if(GROW_BY < 2){
fprintf(stderr, "Growth constant is too small\n");
exit(EXIT_FAILURE);
}
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
while((ch = getchar()) != EOF){
if(ch == '\n'){
printf("%s\n", str_p);
//Here is the error I also tried *(str_p + 0), (*str_p)[0]
printf("%s\n", str_p[0]);
free(str_p);
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
chars_read = 0;
continue;
}
if(chars_read == GROW_BY - 1){
*next_p = 0;
need = next_p - str_p + 1;
tmp_p = (char *)malloc(need + GROW_BY);
if(tmp_p == NULL){
fprintf(stderr, "No initial store\n");
exit(EXIT_FAILURE);
}
strcpy(tmp_p, str_p);
free(str_p);
str_p = tmp_p;
next_p = str_p + need - 1;
chars_read = 0;
}
*next_p++ = ch;
chars_read++;
}
exit(EXIT_SUCCESS);
}
str_p[0]
是一个字符不是字符串
所以你应该使用 %c
printf("%c\n", str_p[0]);
发生这种情况是因为变量参数没有类型安全性,在 printf()
中,如果格式说明符错误,代码将从内存,可能崩溃。
一个有助于调试的有用提示是在 GCC 中启用编译器警告:
gcc -Wall main.c -o main
这将为您的程序显示以下警告。
warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]
printf("%s\n", str_p[0]);
~~ ^~~~~~~~
%c
1 warning generated.
强烈建议使用 -Wall
标志来解决程序中的一些问题。
我想从用户打印出来的字符串中获取它,并访问它的第一个字符,但是使用下面的代码我得到
segmentation fault (Core dumped)
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define GROW_BY 10
int main(){
char *str_p, *next_p, *tmp_p;
int ch, need, chars_read = 0;
if(GROW_BY < 2){
fprintf(stderr, "Growth constant is too small\n");
exit(EXIT_FAILURE);
}
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
while((ch = getchar()) != EOF){
if(ch == '\n'){
printf("%s\n", str_p);
//Here is the error I also tried *(str_p + 0), (*str_p)[0]
printf("%s\n", str_p[0]);
free(str_p);
str_p = (char *)malloc(GROW_BY);
next_p = str_p;
chars_read = 0;
continue;
}
if(chars_read == GROW_BY - 1){
*next_p = 0;
need = next_p - str_p + 1;
tmp_p = (char *)malloc(need + GROW_BY);
if(tmp_p == NULL){
fprintf(stderr, "No initial store\n");
exit(EXIT_FAILURE);
}
strcpy(tmp_p, str_p);
free(str_p);
str_p = tmp_p;
next_p = str_p + need - 1;
chars_read = 0;
}
*next_p++ = ch;
chars_read++;
}
exit(EXIT_SUCCESS);
}
str_p[0]
是一个字符不是字符串
所以你应该使用 %c
printf("%c\n", str_p[0]);
发生这种情况是因为变量参数没有类型安全性,在 printf()
中,如果格式说明符错误,代码将从内存,可能崩溃。
一个有助于调试的有用提示是在 GCC 中启用编译器警告:
gcc -Wall main.c -o main
这将为您的程序显示以下警告。
warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]
printf("%s\n", str_p[0]);
~~ ^~~~~~~~
%c
1 warning generated.
强烈建议使用 -Wall
标志来解决程序中的一些问题。