Struct With Pointer Usage, SEGMENTATION FAULT - c

I have a little problem with using struct array in C. It returns me segmentation fault
struct Yset{
char *unit;
char *name;
char *showValue;
char *fillColor;
char *yData;
};
struct Yset *svg_ysets;
int ySetCounter = 0;
svg_ysets[ySetCounter].unit = malloc(strlen((char*)attribute)+1);
strcpy(svg_ysets[ySetCounter].unit,(char*)attribute);
printf("%s\n", svg_ysets[ySetCounter].unit);
ySetCounter++;
What's wrong with this using? I dont know the number of Ysets so it must be dynamic. Thanks

svg_ysets[ySetCounter].unit = malloc(strlen((char*)attribute)+1);
You are dereferencing pointer to structure while the pointer doesn't point to meaningful place. In other words you didn't allocate space to hold the structure object itself.
// allocate five objects
struct Yset *svg_ysets = malloc (5 * sizeof(struct Yset));
Don't forget to free if you are using dynamically allocated memory somewhere.

Related

Assignment of char array to struct with type casting

I'm working on my C program code to allocate memory without using malloc(). My friend was using a linked list to manage memory, and I do it on this example but I don't know how this type of assignment works in function memory_init().
Here's the main of the example test:
#include <string.h>
int main() {
char region[50];
memory_init(region, 50);
char* pointer = (char*) memory_alloc(10);
if (pointer) memset(pointer, 0, 10);
if (pointer) memory_free(pointer);
return 0;
}
and there's function memory_init():
void memory_init(void *ptr, unsigned size) {
struct metadata *first;
first=(struct metadata*)ptr;
first->next=NULL;
first->prev=NULL;
if (size > sizeof(struct metadata)) first->value=(size - sizeof(struct metadata));
else first->value=0;
first->boo=-1;
zac=first;
}
and there's also used struct:
struct metadata{
short boo; // if -1 free, if 1 memory used
unsigned value; //size of memory block
struct metadata *next;
struct metadata *prev;
};
So I don't know how this part of the code works:
first=(struct metadata*)ptr;
At what I see it it takes a char array sent to the function and retypes it to
a struct and assigns it, but I don't know how assignment like that works?
Does it assign a memory address or what because I don't take how I can retype
char to a struct. Basically I would like to know what happens there.
You have memory; each byte of the memory has an address.
Initially, you have void *ptr, which holds an address to some byte in memory.
When you do first=(struct metadata*)ptr; you tell the compiler, that from now I threat memory under ptr as if this memory holds struct metadata, and you use first to access that memory.
Think about it as mapping data layout defined by struct metadata to some raw memory region.
I'm not sure I understand what you are asking, but "ptr" is a void pointer and "first" is a pointer to the "metadata" struct. So "(struct metadata*)" is used as a cast.

using strcpy to copy a string to a member of a structure via the pointer operator

I'm trying to use strcpy to set values for a char array which is the member of a structure. I want to do this using the pointer operator if possible.
struct my_struct{
char foo[15];
} *a_struct_Ptr;
int main(){
strcpy(a_struct_Ptr -> foo, "test");
return 0;
}
I can compile this code but when I go to run it I get a segmentation fault.
Also it seems to work fine if I don't define the struct as a pointer, for example the following code works fine...
struct my_struct{
char foo[15];
}a_struct;
int main(){
strcpy(a_struct.foo, "test");
return 0;
}
I want to be able to do this with pointers though.
Any feedback is appreciated. Thanks
The problem as many commented, was that I didn't allocate memory for the pointer to my structure.
By preceding my strcpy statement with
a_struct_Ptr = (struct my_struct *) malloc(sizeof(struct my_struct));
I was able to successfully copy a string literal to the char array member of my_struct.
As is good practice, I added free(a_struct_Ptr); after the struct is done being used.

allocating static memory for character pointer defined in struct in C

I have structure with char pointer. I want to allocate static memory to this struct member. How can I do this?
Example:
struct my_data {
int x;
bool y;
char *buf;
};
How to assign 10 bytes static memory to this char pointer? I know malloc to assign dynamic memory allocation. Is this Ok?
struct my_data data;
char buffer[10];
data.buf = &buffer[0];
PS: I am not allowed to change this struct and use malloc to assign dynamic memory.
That will be even simpler (array decays to pointer automatically):
data.buf = buffer;
note that buffer must have an ever-lasting lifetime or you have to make sure that it's not deallocated (i.e. routine where it is declared returns) while you're using it or referencing it.
Allocating from a subroutine and returning will cause underfined behaviour because memory will be deallocated on return.
For instance don't do this (as we often see in questions here):
struct my_data foo()
{
struct my_data data;
char buffer[10];
data.buf = &buffer[0];
return data;
}
int main()
{
struct my_data d = foo(); // buffer is already gone
Bugs introduced by this kind of UB are nasty because the code seems to work for a while, until the unallocated buffer gets clobbered by another function call.

What is the difference between using malloc to allocate memory to a struct pointer and pointing a struct pointer to a struct's memory address?

What is the difference between these two snippets of code?
// Structure
struct file {
int fileSize;
};
int main(void) {
// Variables
struct file *pFile = (struct file*) malloc(sizeof(struct file)); // Declare pointer of type struct file and allocate enough room
pFile->fileSize = 5;
free(pFile);
return 0;
}
and
// Structure
struct file {
int fileSize;
} file1;
int main(void) {
// Variables
struct file *pFile = &file1; // Declare pointer of type struct file and point to file1 struct
pFile->fileSize = 5;
return 0;
}
Is there something big I'm missing here? I'm thinking maybe face value wise these are the same but the underlying memory allocation is different? I just can't grasp it.
There are several differences here:
With malloc you can repeat the call multiple times, and get new valid memory area for your struct; there is only one statically allocated struct
Memory obtained through malloc needs to be freed at the end; statically allocated memory does not need freeing
Statically allocated struct is visible from multiple functions inside the translation unit; memory from malloc is not shared with other functions unless you pass a pointer to them explicitly.
In your first snippet pFile points to dynamically-allocated memory.
In your second snippet, pFile points to a global variable.
Other than the fact that you need to free the dynamic one yourself (which you haven't by the way), the way you interact with the struct is exactly the same in either case.

dynamically allocate memory for pointer to array of structure

hi i have this structure
typedef struct STUDENT
{
char studName[20];
int timeEnter;
int timeUpdate;
}STUDENT;
and the local pointer to array of structure
STUDENT *studArr[100];
I'm trying to allocate memory for the structure by doing reading in the first line of the file then use it to allocate memory for the structure.
fscanf(fp, "%s", &first);
**studArr = (STUDENT**) malloc(sizeof(STUDENT*)*first);
I got an error saying that no operator "=" matches these operands on the allocation line
why am I gettting the error, what did i do wrong here?
thank in advance
I think you're confusing things, it looks like you're declaring an array of pointers, when all you need is a single pointer. Note that as long as you're indexing properly, a pointer to "one" struct is the same as a pointer to a hundred.
You should probably have:
STUDENT *studArr;
then, once you know how many you need (I'm assuming first is the number of students to allocate room for):
studArr = malloc(first * sizeof *studArr);
Also note that no casting is needed.
If you want to allocate an array of 100 students, you have two choices:
struct STUDENT
{
char studName[20];
int timeEnter;
int timeUpdate;
};
struct STUDENT studArr1[100];
... OR ...
struct STUDENT *studArr2 = (struct STUDENT *)malloc (sizeof (struct STUDENT) * 100);
If you just want a pointer, you can say:
struct STUDENT *p = studArr1;
PS:
I deliberately left the "typedef" stuff out so as not to confuse the basic issue (struct vs. array of struct vs pointer to array of struct).
You have defined an array of pointers to struct, not a pointer to an array of struct. The memory for the array is already allocated, as a global array.
The type of **studArr is STUDENT, and hence is not compatible with the expression to the right of the assignment operator, which is casted to (STUDENT**).
You probably meant:
STUDENT **studArr;
[...]
fscanf(fp, "%s", &first);
studArr = (STUDENT**) malloc(sizeof(STUDENT*)*first);
As you are using STUDENT *studArr[100]; then it means you have allocated the memory for 100 pointers for STUDENT structure type.
so for allocating the memory you should try.
studArr =malloc(sizeof(struct STUDENT)*first);
then you can access all the allocated members as studArr[i] ....so on.
You're not exactly clear on what your overall goal is.
First of all, you want to use %d if you want to read in an integer:
int count;
if (fscanf(fp, "%d", &count) != 1) { // error... }
Next, don't use STUDENT as both the struct name and the typdef. Just leave the struct name out:
typedef struct
{
char studName[20];
int timeEnter;
int timeUpdate;
} student_t;
Now, you're going to want just a pointer to an array of student_ts:
student_t* student_array = NULL;
Finally, allocate that array:
student_array = malloc(count * sizeof(student_t));
Now you can use it, like:
strncpy(student_array[0].studName, "Bobby", 20);
Or get a pointer to an individual student:
student_t* bob = &student_array[1];
bob->timeEnter = 42;

Resources