[英]Getting a seg fault but has no idea how to fix it
下面的代碼存在段錯誤,但我真的不知道如何調試它,也許是因為我缺乏C語法,並且我已經讀過TCPL但仍然無濟於事。
#include <stdio.h>
#include <ctype.h>
int main() {
char *str[4];
char c[2];
for (int i = 0; i < 4; i++)
scanf("%s", str[i]);
int find = 0;
while (find <= 2 && *str[0] != '\0' && *str[1] != '\0') {
if (isalpha(*str[0]) && *str[0] == *str[1]
&& *str[0] - 'A' >= 0 && *str[0] - 'A' <= 25) {
find++;
if (find == 1)
c[0] = *str[0];
else if (find == 2)
c[1] = *str[0];
}
str[0]++;
str[1]++;
}
/* ... */
}
這里
char *str[4]; /* what str[0] contains ? some junk data, need to assign valid address */
for (int i = 0; i < 4; i++)
scanf("%s", str[i]); /* No memory for str[i] here */
str
是字符指針數組,它們未初始化,即未指向任何有效地址。 解決此問題的一種方法是為每個char指針分配內存,然后將一些數據放入str[i]
。 例如
char *str[4];
for (int i = 0; i < 4; i++) {
str[i] = malloc(MAX); /* define MAX value as per requirement */
scanf("%s", str[i]); /* Now str[i] has valid memory */
}
一旦完成了動態內存的工作,就不要忘記通過為每個char指針調用free(str[i])
來釋放動態內存,以避免內存泄漏 。
您忘記為字符串分配的內存。
您的代碼具有動態分配的內存。
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h> //needed for malloc and free
int main() {
char *str[4];
//allocate memory
for (int i = 0; i < 4; ++i) {
//allocate 128B per string
str[i] =(char*) malloc(128 * sizeof(char));
//here you should check if malloc was succesfull
//if malloc failed you schould free previously allocated memory
}
char c[2];
for (int i = 0; i < 4; i++)
scanf("%s", str[i]);
int find = 0;
while (find <= 2 && *str[0] != '\0' && *str[1] != '\0') {
if (isalpha(*str[0]) && *str[0] == *str[1]
&& *str[0] - 'A' >= 0 && *str[0] - 'A' <= 25) {
find++;
if (find == 1)
c[0] = *str[0];
else if (find == 2)
c[1] = *str[0];
}
str[0]++;
str[1]++;
}
//delete memory
for (int i =0; i < 4; ++i) {
free(str[i]);
}
/* ... */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.