xbe*_*nch 1 c pointers list void-pointers
我正在尝试写一个简单的列表.我有下一个代码:
#include "stdio.h"
#include "stdlib.h"
typedef struct _anObject {
void* data;
struct _anObject* previous;
struct _anObject* next;
} object_t;
typedef struct _aHead {
object_t* first;
object_t* current;
object_t* next;
object_t* last;
int index;
int size;
} head_t;
head_t* new_list(void)
{
head_t* list = malloc(sizeof(head_t));
list->first = NULL;
list->current = NULL;
list->last = NULL;
list->index = -1;
list->size = 0;
return list;
}
void add_object_to_list(head_t* list, object_t* object)
{
if (list->size == 0)
{
object->next = NULL;
object->previous = NULL;
list->first = object;
list->current = object;
list->last = object;
list->index = 0;
list->size = 1;
}
else if (list->size > 0)
{
object->previous = list->last;
object->next = NULL;
list->current->next = object;
list->current = object;
list->last = object;
list->size +=1;
list->index = list->size - 1;
}
}
object_t* createIntObject(int value)
{
int* data = &value;
object_t* object = malloc(sizeof(object_t));
object->data = data;
return object;
}
int main(int argc, char** argv)
{
head_t* list = new_list();
object_t* obj;
obj = createIntObject(22);
add_object_to_list(list, obj);
obj = createIntObject(44);
add_object_to_list(list, obj);
fprintf(stderr, "size number: %i\n", list->size);
fprintf(stderr, "First data value on the list: %i\n", *(int*) list->first->data);
fprintf(stderr, "Last data value on the list: %i\n", *(int*) list->last->data);
free(list);
free(obj);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我编译时没有任何警告或错误,但是当我运行代码时,我获得了下一个而不是想要的结果:
size number: 2
Current data value on the list: 0
Current data value on the list: 0
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?任何帮助将不胜感激
错误发生在createIntObject
,返回指向函数参数的指针:
object_t* createIntObject(int value) { /* deobfuscated */
object_t* object = malloc(sizeof(object_t));
object->data = &value; // <--
return object;
}
Run Code Online (Sandbox Code Playgroud)
一旦函数返回,访问局部变量的指针(包括函数参数)会产生未定义的行为.相反,为整数值分配空间malloc
,并将其分配给object->data
.
这是一个常见的初学者错误.有关更多信息,请参阅参考问题或local-variables标记.
其他几个注释:如果你使用printf
和malloc
,你必须 #include <stdio.h>
和#include <stdlib.h>
.
确保您的编译器默认设置为识别这些错误.例如,除非您完全确定编译器内部和C标准,否则编译程序是个好主意gcc -std=c99 -pedantic -Wall -Werror
.
此外,成功的程序按惯例返回0,否则返回错误代码.