Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Segmentation fault 1

Status
Not open for further replies.

mattias1975

Programmer
Jul 26, 2004
36
SE
Hello!

After the last fgets i get the message Segmentation fault from the operating system. What am i doing wrong?

(This is ofcaurse only a part of my application)

typedef struct mystruct
{
char a[10], b[10], c[10];
struct mystruct *link;
} mystruct;

struct mystruct* inputFunction()
{
struct mystruct *hello;
char *str;

str = malloc(100);
hello = (struct mystruct *)malloc(sizeof(struct mystruct));

printf("\na: ");
fgets(hello->a, 10, stdin);

printf("b: ");
fgets(hello->b, 10, stdin);

printf("c: ");
fgets(hello->c, 10, stdin);

free(hello);
free(str);

return hello;
}
 
1. Please use the TGML [tt][ignore]
Code:
[/ignore][/tt]
tags when posting code.

Several things need to be fixed.
1. str is unused - why bother allocating and freeing it?

> hello = (struct mystruct *)malloc(sizeof(struct mystruct));
2. Do NOT cast the return result of malloc in C
At worst, it masks your failure to include stdlib.h to prototype the function properly. In this case, you'll get a warning about casting int to a pointer, which the correct fix is to include the appropriate header.

If on the other hand it complains about casting void* to a pointer, it means you're compiling your code with a C++ compiler. In this case, start using a C compiler.

> return hello;
3. referencing a pointer after you have called free() on it is a serious error.

> (This is ofcaurse only a part of my application)
Then it should be read in the context of my previous reply to another post.

--
 
Ok. But should i free it after i return it?
Is tat possible?

return hello;
free(hello);
 
> Ok. But should i free it after i return it?
Yes, the caller free's it, like so.

Code:
struct mystruct *someptr = inputFunction();
// do something
free( someptr );

--
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top