Мне нужно было реализовать конкретный ADT, strqueue, для моего класса CS сегодня, поэтому я написал две функции: create_StrQueue() и add_to_back (StrQueue sq, const char * str). К сожалению, когда я вызываю create_StrQueue в add_to_back, я получаю ошибку seg, и я не могу понять, почему именно. Вот код, который я написал для этих двух функций:Ошибка сегментации с помощью Malloc
[править] Я должен, вероятно, malloc tempWord в add_to_back.
#include <stdlib.h>
// A strqueue is an ADT consisting of words
struct strqueue{
StrQueue back; // last StQueue in queue
StrQueue next; // next StrQueue in queue
char* word; // stored string
int length; // length of entire queue
};
typedef struct strqueue* StrQueue;
StrQueue create_StrQueue(void){
StrQueue retq = malloc(sizeof(struct strqueue)); // get memory for a new strqueue
retq->word = malloc(sizeof(char*));
retq->word = NULL;
retq->back = retq; // set back pointer to itself
retq->next = NULL; // nothing after this strqueue yet
return retq;
}
void add_to_back(StrQueue sq, const char* str){
char* tempWord;
sq->length++;
for(int i=0; str[i]; ++i) tempWord[i]=str[i]; // copy string for the new strqueue
if(sq->word==NULL) sq->word = tempWord; // input strqueue was empty
// input StrQueue was not empty, so add a new StrQueue to the back
StrQueue new = create_StrQueue(); // results in seg fault
new->word = tempWord;
sq-back->next = new; // swaping pointers around to add malloced StrQueue to the back
sq->back = next;
}
Я в недоумении, и поэтому я надеюсь, что кто-то может уточнить, что именно происходит, потому что, когда я бегу основной, как это;
int main(void){
char* str1 = "Hello";
StrQueue sq = create_StrQueue(); // does not cause seg fault
add_to_back(sq, str1);
}
вызов create_StrQueue() впервые работает нормально.
1) 'tempWord [i] = str [i];' неверно. – BLUEPIXY
How-so? Я запустил небольшой фрагмент кода, чтобы распечатать tempWord после этого цикла, чтобы убедиться, что он скопировал строку, и это действительно так. – Plopperzz
1) Площадь для хранения не гарантируется. – BLUEPIXY