strlen and malloc: C memory leaks

前端 未结 1 1757
遥遥无期
遥遥无期 2021-01-27 08:37

This question is null and void! I was not properly freeing the Students! I will accept the answer that revealed this to me as quickly as I am allowed!

I\'m new to C and

相关标签:
1条回答
  • 2021-01-27 09:30

    There are a few problems here:

        newStudentp -> last_name = (malloc(strlen(last_name)));
        newStudentp -> first_name = (malloc(strlen(first_name)));
    

    strlen only gives the length up to but not including the terminating '\0'. But that must be stored too, so you should use strlen(last_name) + 1 in both cases.

    Also, your strncpy() should better be done using the size of the allocated buffer and not of the source string, so you can avoid writing past the high boundary of the array. But since you already used malloc(strlen(...) + 1), you can simply use strcpy() here.

    0 讨论(0)
提交回复
热议问题