I'm trying to malloc an array inside a struct but I keep getting segmentation errors when I run the program.
The compares function is just something I'm testing so it shouldn't be a part of the problem
typedef struct {
char *string;
} prod_t;
int
main(int agrc, char **argv){
int i = 0;
prod_t *c = NULL;
char str2[100] = "abcd";
c->string = (char *) malloc( 5 * sizeof(char));
strcpy(c->string,str2);
compares(c->stock,str2,i);
return 0;
}
The problem is that you're allocating space for the string, but you're not allocating the struct at all. c remains set to NULL and you're trying to dereference it.
Allocate space for the struct before assigning to its members
prod_t *c = malloc(sizeof(prod_t));
And, as a sidenote for your next-to-fix error: this field doesn't exist
c->stock
You need to allocate space for the struct before you can assign to the string member:
prod_t *c = malloc(sizeof(prod_t));
Also see Do I cast the result of malloc?
First of all, don't cast result of malloc. You only need to do that in C++. In C, it can actually hide potential problems.
Second of all, you need to allocate (or statically declare) your structure.
Third, c->stock doesn't exist. You probably meant c->string.
typedef struct {
char *string;
} prod_t;
int
main(int agrc, char **argv) {
int i = 0;
prod_t *c = malloc( sizeof( prod_t ));
char str2[100] = "abcd";
c->string = malloc( 5 * sizeof(char));
strcpy(c->string,str2);
compares(c->string,str2,i);
return 0;
}
Related
I ran into an interesting problem today. This snippet prints garbage (e.g. ?Y#??):
typedef struct {
int field_1;
int field_2;
int field_3;
char *arr[64];
} test;
int main(void) {
test *test = malloc(sizeof(test));
char *str = malloc(sizeof(char) * 6);
strncpy(str, "hello", 5);
str[5] = '\0';
test->arr[0] = str;
printf("%s\n", test->arr[0]);
}
However, changing test to:
typedef struct {
int field_1;
int field_2;
char *arr[64];
} test;
(removing field_3) prints the expected result (hello).
Even stranger, swapping the malloc calls like so:
char *str = malloc(sizeof(char) * 6);
test *test = malloc(sizeof(test));
prints the correct result regardless of the size of test.
What the heck is going on here?
I'm using clang-1200.0.31.1.
The problem is on this line:
test *test = malloc(sizeof(test));
Here, sizeof(test) is referring to the variable named test, not the type named test. So you're getting the size of a pointer, not the size of the struct. As a result, you're not allocating enough space for the object in question and you write past the end of allocated memory, invoking undefined behavior.
Give either the typedef or the variable a different name, for example:
typedef struct {
int field_1;
int field_2;
int field_3;
char *arr[64];
} test_type;
...
test_type *test = malloc(sizeof(test_type));
this is how I define struct.
struct urlFormat
{
int port;
char *host;
char *path;
int cat;
char *status;
};
this is how I initialize strcut and allocate the space for the pointer.
struct urlFormat *res;
res = malloc(sizeof(struct urlFormat));
when I used memcpy() function, it reported segmentation fault.
char *ptr1 = (char *)url;
int len = strlen(ptr1);
memcpy(res->host, ptr1, len);
I don't know how to solve it.
res->host is just a pointer (that is not pointing to anything yet).
Until res->host is pointing to some valid memory you can't memcpy to it.
You can either malloc some memory res->host = malloc(len + 1);(+1 for the 0 terminator and sizeof(char) is always 1 so omit it) or in this case just use res->host = strdup(ptr1);
I'm having trouble initializing a string of characters belonging to a struct. "Expression must have a modifiable lvalue". Do I need to use strcopy? I am not quite sure how to utilize this. Here is my code:
typedef struct {
char name[50];
int attackDamage;
int magicDamage;
int defense;
int power;
int type;
} ITEM;
int main() {
ITEM item[10];
char itemset[5][5] = { 0 };
char champion1[] = "Gnar";
char champion2[] = "Vi";
char champion3[] = "Fizz";
char champion4[] = "Draven";
char champion5[] = "Braum";
item[0].name = "Brutalizer"; // Having issues here
}
EDIT: I did this and seems there isn't anymore errors. Is this the proper way?
strcpy(item[0].name, "Brutalizer");
item[0].name is an array, you cannot assign a pointer (string literal) to an
array. You need to copy the contents, in this case with strcpy for example:
strcpy(item[0].name, "Brutalizer");
Or if the length of the source is not know beforehand, then you can use
strncpy to avoid buffer overflows:
strncpy(item[0].name, "Brutalizer", sizeof item[0].name);
item[0].name[sizeof(item[0].name) - 1] = '\0'; // make sure that it's \0-terminated
or you can use snprintf
snprintf(item[0].name, sizeof item[0].name, "Brutalizer");
I can't quite figure out how to do this, I've tried this and several variations and some will compile and seemingly work ok but I'll get very random segfaults and it has something to do with the way I'm declaring these structs. All the info in the structs are dynamic. Please let me know the proper way to do this, thank you.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char* s2string1;
char* s2string2;
int s2int1;
} struct2;
typedef struct
{
char* s1string1;
char* s1string2;
struct struct2* mystruct;
int int1;
} struct1;
struct struct2* RetS2(char* CopyMe)
{
int* Array = (int*) malloc (sizeof (int) * 5);
Array[0] = strlen (CopyMe);
struct struct2* S2 = (struct struct2*) malloc ( sizeof (struct2) );
S2->s2int1 = Array[0];
return S2;
}
struct struct1* RetS1()
{
struct struct1* S1 = (struct struct1*) malloc ( sizeof (struct1) );
struct struct2* S2 = RetS2();
S1->mystruct = S2;
S1->int1 = S2->S2int1;
return S1;
}
int main()
{
struct struct1 Top = RetS1();
if (Top->mystruct->s2int1 == 10)
// do something
return 0;
}
Your code has multiple issues:
This is the main issue:
RetS2's function definition is
struct struct2* RetS2(char* CopyMe)
which means that it expects a char* as its first argument. But when you call it:
struct struct2* S2 = RetS2();
you don't pass an arguments. This invokes Undefined Behavior.
Here:
int* Array = (int*) malloc (sizeof (int) * 5);
You allocate memory for 5 ints. You use the first element of the array and stops using it. You also forgot the free the allocated memory for Array.
The cast in malloc (and family) is not required in C.
You don't free the malloced memory for S2 and S1.
In redis there is a struct called sdahdr:
struct sdahdr
{
int len;
int free;
char buf[];
}
Why not use char *buf instead, and why is sizeof(sdahdr) == 8 instead of 12?
The char buf[] is a placeholder for a string. Since the max length of the string is not known at compiletime, the struct reserves the name for it, so it can be properly adressed.
When memory is allocated at runtime, the allocation must include the length of the string plus the sizeof the struct, and then can pass around the structure with the string, accessible via the array.
char *s = "test";
struct sdahdr *p = malloc(sizeof(struct sdahdr)+strlen(s)+1);
strcpy(p->buf, s);