[SOLVED] C malloc() runtime assertion problems (gcc v4.4.5, target: x86_68-linux-gnu)
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
C malloc() runtime assertion problems (gcc v4.4.5, target: x86_68-linux-gnu)
Hello all,
I had a C programme which was throwing strange errors at runtime - the smallest example which I have found to throw this error is as follows:
Code:
#include <stdlib.h>
int main(){
unsigned short int* myIntArray;
myIntArray = malloc(sizeof(unsigned short int)*200);
int d;
for(d=0;d<sizeof(unsigned short int)*103;d++){ // ***
myIntArray[d] = 0;
}
char* myCharArray;
myCharArray = malloc(sizeof(char)*2); //Error thrown by this line
return 0;
}
The strange thing is, if I change the line marked *** to:
Code:
for(d=0;d<sizeof(unsigned short int)*102;d++){
then no error is thrown. Using gdb, I've looked at the memory at myIntArray[101], myIntArray[102], myIntArray[103] and myIntArray[104], and all of them are 0. My guess is I'm missing something in the code which results in me writing off the end of myIntArray, but I can't see what it is for the life of me...
Thank you very much, ntubski I had thought that array[5] accessed the 5th byte after array, not the 5th element after array. And thanks for the tip Sergei; I've come from a python/java-ey background and this is my first real experience with low-level languages, so I appreciate the help
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.