In this function,
void
allocateMem(struct myStruct *struct1)
{
struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
}
struct1 is passed by value. Any changes you make to it in the function are not visible from the calling function.
A better alternative:
struct myStruct* allocateMem()
{
struct myStruct *struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
return struct1;
}
Change the calling function to:
int
main(int argc, char *argv[])
{
struct myStruct *struct1 = allocateMem();
printf("number: %d\n", struct1->number);
// Make sure to free the memory.
free(struct1);
return 0;
}
Answer from R Sahu on Stack OverflowIn this function,
void
allocateMem(struct myStruct *struct1)
{
struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
}
struct1 is passed by value. Any changes you make to it in the function are not visible from the calling function.
A better alternative:
struct myStruct* allocateMem()
{
struct myStruct *struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
return struct1;
}
Change the calling function to:
int
main(int argc, char *argv[])
{
struct myStruct *struct1 = allocateMem();
printf("number: %d\n", struct1->number);
// Make sure to free the memory.
free(struct1);
return 0;
}
A pointer is just an integer in reality, when you pass in struct1 to your function since struct1 is null you are just passing in a 0 to your function in reality. that value gets passed on the stack and you do a heap allocation and update the stack value with the new address. but when you return from the function, that value just gets popped of the stack and you have leaked that memory. the value of struct1 in main (which is also on the stack still keeps its value 0(NULL). so you have to pass in a pointer to your pointer if you want to update that value, or what might be easier is just to return the malloc'd pointer from your function.
This is one way you could modify your function to work:
#include <stdio.h>
#include <stdlib.h>
struct myStruct
{
int number;
};
struct myStruct*
allocateMem()
{
struct myStruct* struct1 = malloc(sizeof(struct myStruct));
struct1->number = 500;
printf("struct1->number: %d\n", struct1->number);
return struct1;
}
int
main(int argc, char *argv[])
{
struct myStruct *struct1 = allocateMem();
printf("number: %d\n", struct1->number);
return 0;
}
Why is it so important to create space with malloc for structs so the struct will be on the heap. Why cant the struct be created without malloc and stay on the stack ? We are being thought this concept in school, but i dont understand why.
// A simple C program for traversal of a linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// This function prints contents of linked list starting from
// the given node
void printList(struct Node* n)
{
while (n != NULL) {
printf(" %d ", n->data);
n = n->next;
}
}
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
printList(head);
return 0;
}Videos
I just defined a new struct type typedef struct graph_struct {} struct; and I need to make one of them in my main function. There are two options for a constructor:
-
Declare a
graphinmain(), and pass its address to the constructor. Return nothing. -
Pass nothing to the constructor,
mallocagraphinside of it, and return a pointer to thegraph.
I prefer 2), but I think that memory on the heap is slower to work with than memory on the stack. And my program does need to be really fast.
Is there any reason to prefer one over the other?
My favorite:
#include <stdlib.h>
struct st *x = malloc(sizeof *x);
Note that:
xmust be a pointer- no cast is required
- include appropriate header
You're not quite doing that right. struct st x is a structure, not a pointer. It's fine if you want to allocate one on the stack. For allocating on the heap, struct st * x = malloc(sizeof(struct st));.
The same way you declare any variable on the stack:
struct my_struct {...};
int main(int argc, char **argv)
{
struct my_struct my_variable; // Declare struct on stack
.
.
.
}
To declare a struct on the stack simply declare it as a normal / non-pointer value
typedef struct {
int field1;
int field2;
} C;
void foo() {
C local;
local.field1 = 42;
}
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
This isn't just a struct declaration, it's also a variable declaration... it's the same as:
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
};
struct USER *administrator;
So, when you subsequently use sizeof(administrator), you'll get "the size of a pointer"... which is most likely not what you want.
You probably wanted to do something more like this:
struct USER {
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
};
int main(void) {
struct USER *administrator;
administrator = malloc(sizeof(*administrator));
/* - or - */
administrator = malloc(sizeof(struct USER));
/* check that some memory was actually allocated */
if (administrator == NULL) {
fprintf(stderr, "Error: malloc() returned NULL...\n");
return 1;
}
/* ... */
/* don't forget to free! */
free(administrator)
return 0;
}
sizeof(*administrator) and sizeof(struct USER) will both give you "the size of the USER structure", and thus, the result of malloc() will be a pointer to enough memory to hold the structure's data.
struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} *administrator;
This defines administrator as a pointer variable. But, from the other code
administrator *newStruct = (administor*)malloc(sizeof(administrator));
It seems you want to use that as a type. To do so, you can make use of the typedef.
typedef struct USER{
int human_id_number;
char first_name_letter;
int minutes_since_sneezing;
} administrator;
and then use
administrator *newStruct = (administrator *)malloc(sizeof(administrator));
In this case, however, is it possible to create a new instance of this struct on the heap, or would I need to define a constructor? Is there a way to create things on the heap without the new operator?
As answered before, you can create a new instance on the heap either via new or with malloc.
Or, better yet: is it unnecessary for me to cling so tightly to the notion that I shouldn't define member functions for structs?
This is the more interesting question. The major (only?) difference between struct and class in c++ is the
default access specifier. That is, struct defaults to public access and class defaults to private. In my opinion, this is the difference that should determine which of the two you use. Basically, if users should access the members directly, then it should be a struct.
If, for example, you have no member functions, then obviously the intention is for the object's members to be accessed directly and so it would be a struct. In the case of an object that is just a small private helper for the implementation of its outer class, as in your example, then even if it has member functions it is often clearest to allow the outer class access to its members and so it should be a struct. Often with these classes the implementation of the outer class is tightly coupled to the implementation of the inner class and so there is no reason to hide the one from the other.
So, for trivial (e.g. std::pair) objects or those whose use is limited (as in a private inner class) default access to members can be a good thing, and in these cases I would make them structs.
Even if you don't define a constructor, the compiler will create a default one and so you can use operator 'new':
Node *n = new Node;
AFAIAC, a struct is a class, except that its "publicness" default is reversed.
Yes, you've created a struct on the heap. You haven't populated it correctly, and you are going to face problems deleting it - I'm not sure whether the homework covered that or not. As it stands, you're more likely to get memory corruption or, if you're lucky, a memory leak than to release one of these strings.
Code that works with standard C89 and C99
Your code, somewhat fixed up...
typedef
struct String {
int length;
int capacity;
char *ptr;
} String;
char* modelstrdup(char* src){
int length = strlen(src);
char *space = malloc(sizeof(String) + length + 1);
//String *string = space; // Original code - compilers are not keen on it
String *string = (String *)space;
assert(space != 0);
string->ptr = space + sizeof(String); // or sizeof(*string)
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
This code will work in C89 as well as C99 (except for the C99/C++ comments). You can probably optimize it to work with the 'struct hack' (saves a pointer in the structure - but only if you have a C99 compiler). The assert is sub-optimal error handling. The code doesn't defend itself against a null pointer for input. In this context, neither the length nor the capacity provides any benefit - there must be other functions in the suite that will be able to make use of that information.
As already intimated, you are going to face problems deleting the string structure when the value handed back is not a pointer to the string. You have some delicate pointer adjustments to make.
Code that works with standard C99 only
In C99, section 6.7.2.1 paragraph 16 describes 'flexible array members':
As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member. With two exceptions, the flexible array member is ignored. First, the size of the structure shall be equal to the offset of the last element of an otherwise identical structure that replaces the flexible array member with an array of unspecified length.106) Second, when a . (or ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member, it behaves as if that member were replaced with the longest array (with the same element type) that would not make the structure larger than the object being accessed; the offset of the array shall remain that of the flexible array member, even if this would differ from that of the replacement array. If this array would have no elements, it behaves as if it had one element but the behavior is undefined if any attempt is made to access that element or to generate a pointer one past it.
106 The length is unspecified to allow for the fact that implementations may give array members different alignments according to their lengths.
Using a 'flexible array member', your code could become:
typedef
struct String {
int length;
int capacity;
char ptr[];
} String;
char* modelstrdup(char* src){
int length = strlen(src);
String *string = malloc(sizeof(String) + length + 1);
assert(string != 0);
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
This code was accepted as clean by GCC 4.0.1 apart from a declaration for the function (options -Wall -Wextra). The previous code needs a cast on 'String *string = (String *)space;' to tell the compiler I meant what I said; I've now fixed that and left a comment to show the original.
Using the 'struct hack'
Before C99, people often used the 'struct hack' to handle this. It is very similar to the code shown in the question, except the dimension of the array is 1, not 0. Standard C does not allow array dimensions of size zero.
typedef struct String {
size_t length;
size_t capacity;
char ptr[1];
} String;
char* modelstrdup(char* src)
{
size_t length = strlen(src);
String *string = malloc(sizeof(String) + length + 1);
assert(string != 0);
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
Code that uses a GCC non-standard extension to C89 and C99
The zero-size array notation is accepted by GCC unless you poke it hard - specify the ISO C standard and request pedantic accuracy. This code, therefore, compiles OK unless you get to use gcc -Wall -Wextra -std=c99 -pedantic:
#include <assert.h>
#include <stdlib.h>
#include <string.h>
typedef
struct String {
int length;
int capacity;
char ptr[0];
} String;
char* modelstrdup(char* src){
int length = strlen(src);
String *string = malloc(sizeof(String) + length + 1);
assert(string != 0);
string->length = length;
string->capacity = length + 1;
strcpy(string->ptr, src);
return string->ptr;
}
However, you should not be being trained in non-standard extensions to the C language before you have a thorough grasp of the basics of standard C. That is simply unfair to you; you can't tell whether what you're being told to do is sensible, but your tutors should not be misguiding you by forcing you to use non-standard stuff. Even if they alerted you to the fact that it is non-standard, it is not fair to you. C is hard enough to learn without learning tricksy stuff that is somewhat compiler specific.
You have allocated some memory on the heap, but you're not using it as if it were your structure. The string variable in your function is of type char *, not of type struct String. I think you're duplicating the functionality of strdup() reasonably enough, but I don't understand the reason for the structure.
Note: You should probably check your call to malloc() for failure, and return appropriately. The man page for strdup() should explains exactly what your function should be doing.
struct st *q; declares a pointer to struct only. q pointing at unknown memory location. You need to allocate memory for q too otherwise it will invoke undefined behavior.
struct st *q = malloc(sizeof(struct st));
Also , q->p=&i; will cause memory leak.
to determine which line of code segfaults your program one of the most easiest tricks is to printf("something distingishable") after a suspicous line.
By doing so, you would have found out, that the first access to q will fail.
In the stack:
void func()
{
mystruct m;
...
}
// The address of 'm' is within the stack memory space
In the heap:
void func()
{
mystruct* m = malloc(sizeof(mystruct));
...
}
// The value of 'm' is an address within the heap memory space
In the data-section:
mystruct m;
static mystruct m;
void func()
{
static mystruct m;
...
}
// The address of 'm' is within the data-section memory space
In the code-section:
const mystruct m;
const static mystruct m;
void func()
{
const mystruct m;
...
}
void func()
{
const static mystruct m;
...
}
// The address of 'm' is within the code-section memory space
UPDATE:
Although not directly related to your question, please note that the above rule for const is not entirely accurate, as this keyword has in fact two purposes:
- Allocate a variable in the (read-only) code-section of the program.
- Prevent you (the programmer) from writing erroneous code, such as changing the value of a variable that you initially intended to keep constant throughout the execution of your program.
But feature #1 is really up to the compiler in use, which may place it elsewhere, depending on your project configuration. For example, sometimes you might want to declare a constant variable just for the sake of feature #2, while feature #1 is not feasible due to insufficient memory space in the code-section.
The stack. You have to use malloc/calloc to create a heap variable.