Isan Rivkin
Isan Rivkin

Reputation: 167

How to create memory allocation in a struct for a string in c?

I have a bit of an issue. I'll explain, I'm trying to create a dynamic memory allocation for a string inside a struct and print it. The thing is, it doesn't care about the size I dynamically allocate.

For example, I create a string in the size of size 6, but it let's me insert 15 chars and prints them all.

So basically, it doesn't limit me on the string size, why's so?

typedef struct{
    int grade;
    int id;
    int arr[5];
    char *str;
}student;

int main(){
    puts("How many many letters in char?\n");
    scanf("%d", &num);
    getchar();
    student1.str = (char *)malloc(sizeof(char)*num+1);
    gets(buffer);
    strcopy(student1.str, buffer);
}

BTW, I tried to keep the code clear as possible for you guys/ladies, just with the main things I need. I know I didn't free the memory or checked if allocation failed etc...

Upvotes: 1

Views: 175

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

First to say, please see this discussion on why not to cast the return value of malloc() and family in C..

Coming to the main issue here, out of bound memory access causes undefined behavior.

So basically, it doesn't limit me on the string size, why's so?

There is nothing in the C standard itself to prevent you from accessing out of bound memory (i.e, accessing the memory which is not allocated to your process), but any attempt to do so will lead to UB. Don't do that.

That said,

  1. Never use gets(), it suffers from buffer overrun issues, use fgets() instead.

  2. sizeof(char) is defined to be 1 in C. Using that as a multiplier is redundant.

Upvotes: 4

Kavli
Kavli

Reputation: 304

When you use C, a major part of the job of programming, is to make sure that any data that hits your allocated memory will actually fit. This is why C programming can be such a pain. It also requires you to free your memory when you don't use it anymore, which you forgot in your example.

Upvotes: 1

CIsForCookies
CIsForCookies

Reputation: 12817

The malloc is giving you the permission to write to the memory but you can try and write without permission. That is what you just did. It may work and it may not, but If you will use malloc properly you should be able to run this code run-time-error-free

Upvotes: 1

Related Questions