sending a struct to a function, previously defined with a pointer
Edit: Forget it. it was another part of the code (actually the problem was a secondary element. another pointer but not allocated with malloc, just declared, so i think the memory was allocated in another place). the example now can compile.
thanks guys. im sorry for my typos but english isnt my native language(isnt a good escuse but i will try harder) .
hi. i want to pass the some elements (in a struct)to a function but i cannot read the elements in any way(seg faults)
#define _FI开发者_运维技巧LE_OFFSET_BITS 64
#define _LARGEFILE_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include "pcre.h"
#include <arpa/inet.h>
#define BUFFER 1512
typedef struct OCR {
unsigned long int ocr;
struct OCR * prev;
struct OCR * next;
} ip_ocr;
int sending (ip_ocr * tmp) {
printf("%p\n",tmp); //this outpuut
printf("%lu",tmp->ocr); // at this point i get a seg fault
return 0;
}
int main () {
ip_ocr * list;
list=malloc(sizeof(ip_ocr));
list->ocr=1;
list->next=NULL;
list->prev=NULL;
sending(list);
}
It worked on my machine after a few fixes.
Include system headers:
#include <stdio.h>
#include <stdlib.h>
Add semicolons after these lines:
printf("%lu",tmp->ocr);
return 0;
Added (unnecessary) typecast to value returned from malloc:
list=(ip_ocr*)malloc(sizeof(ip_ocr)); /* oops, not needed */
I think that you must have ignored a warning that the return of malloc
has been taken to be an int
. Your list
then goes completely wrong.
- include the correct header files
- always compile with
-Wall
or equivalent - improve your code until it doesn't spit out any warning at all
Compiling with -Werror-implicit-function-declaration
and -Werror=return-type
prevents these kind of things happening in C.
精彩评论