This small C program is crashing every single time.
It is supposed to allocate a chunk of memory under the form of a 3D grid composed of many structures (cells) disposed in memory in a 3D-friendly pattern. The structs will be populated with position data.
I don't know why it crashes. It returns this number: c0000005.
#include <stdio.h>
#include <malloc.h>
typedef struct {
int coords[3];
} cell;
int main() {
int x=4, y=8, z=6;
int volume=x*y*z;
cell *arr=(cell*)calloc(volume,sizeof(cell));
int u=0,v=0,w=0;
int index;
for (w=0; w<z; w++) {
for (v=0; v<y; v++) {
for (u=0; u<x; u++) {
//printf("%d %d %d\n", u, v, w);
index=u+v*y+w*y*z;
arr[index].coords[0]=u;
arr[index].coords[1]=v;
arr[index].coords[2]=w;
//getchar();
}}}
printf("All done.\n");
return 0;
}
The problem is index=u+v*y+w*y*z;.
It should be index=u+v*x+w*y*x;.
So #nos is right. It triggers a segmentation fault because 6=z>x=4 and index becomes too large.
Related
There are some problems thatconfuse me:
The callee function needs return a structure, but there is not a structure statment in caller function.
If i have to write the declaration in the calling function,it can not be called packaging function.
If i return a structure pointer by callee function, but the structure is in the stack of the called function and will be destroyed after the end, which is not safe. Sometimes i get some warning or even wrong!
I have a limited ideas but it not good. I put the structure into the heap by malloc and return the void*pointer. But this gave birth to a new problem :after each call to this function, in the caller, I cannot release the heap through the free() function,the complier can not identify variable name of structure pointer. I think it verey dangerous. I want when the callee function quit,it can be released by itself.
This is the first time I came to this website to ask questions and I just came into contact with c language,If there is something stupid please point it out.
I have to write the structure declaration outside. This program for judging prime number, and I want to package the founction "judging_number". I do not want to write the structure declaration when I want to call the founction "judging_number".
Please give me some help, I would be very grateful.
Sorry, this is my fault. I compiled it with clang++, I saved it as *.cpp, but I wrote c code in it.
What I mean is, can I put the declaration in the called function to realize the function modularization, how can I not declare a structure before calling the function? Is there any way I can not write a declaration. Like use founction in stdio.h.It is as convenient as using the functions of the standard library. Only need to write a line of function call and pass parameters, the called function can return multiple results.
#include <stdio.h>
struct boundary{
int L;
int R;
};boundary *range;
int *get_number()
{
int *nPtr = (int *)malloc(sizeof(int));
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", nPtr);
if (*nPtr == 1)
{
exit(1);
}
} while (*nPtr < 1);
printf("The object is %d\r\n", *nPtr);
return nPtr;
}
int judg_number(int N,boundary range){
if (N%range.L==0&&N!=2){
printf("The number %d is a composite number.\r\n", N);
}
else{
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
boundary* get_range(int N){
boundary *Ptr = (boundary *)malloc(sizeof(boundary));
*Ptr = {2,N-1};
printf("The range is between %d and %d .\r\n", Ptr->L, Ptr->R);
return Ptr;
}
int main(int argc,char**argv,char**env){
int*N;
while(1){
N=get_number();
range=get_range(*N);
judg_number(*N, *range);
free(N);
free(range);
}
getchar();
getchar();
return 0;
}
You dont need dynamic memory allocation here. If you want to retun an int, retun an int. If you want to retun a stuct return a struct.
You probably want this:
#include <stdio.h>
#include <stdlib.h>
struct boundary {
int L;
int R;
};
struct boundary range;
int get_number()
{
int n;
do
{
printf("Please enter a vaild number for judging prime number.Or enter the number 1 to quit.\r\n");
scanf("%d", &n);
if (n == 1)
{
exit(1);
}
} while (n < 1);
printf("The object is %d\r\n", n);
return n;
}
int judg_number(int N, struct boundary range) {
if (N % range.L == 0 && N != 2) {
printf("The number %d is a composite number.\r\n", N);
}
else {
printf("The number %d is a prime number.\r\n", N);
}
return 0;
}
struct boundary get_range(int N) {
struct boundary b = { 2, N - 1 };
printf("The range is between %d and %d .\r\n", b.L, b.R);
return b;
}
int main(int argc, char** argv, char** env) {
int N;
while (1) {
N = get_number();
range = get_range(N);
judg_number(N, range);
}
getchar();
getchar();
return 0;
}
BTW:
boundary get_range(int N) {... is invalid in C but valid in C++. In C it should be struct boundary get_range(int N) {...
I'm fully prepared to be told that I'm doing something stupid/wrong; this is what I expect.
I'm getting a feel for structures and coming a cropper when it comes to accessing the fields from the pointers. Code to follow.
matrix.h:
#ifndef MATRIX_H_INCLUDED
#define MATRIX_H_INCLUDED
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
#endif // MATRIX_H_INCLUDED
main.c:
#include <stdio.h>
#include <stdlib.h>
#include "matrix.h"
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v;
v.size = size;
v.vector = vector;
return &v;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
return EXIT_SUCCESS;
}
So this is a very simple program where I create a vector structure of size 3, return the pointer to the structure and then print its size. This, on the first print instance is 3 which then changes to 2686668 on the next print. What is going on?
Thanks in advance.
You are returning a pointer to a local variable v from vector_new. This does not have a slightest chance to work. By the time vector_new returns to main, all local variables are destroyed and your pointer points to nowhere. Moreover, the memory v.vector points to is also a local array vector. It is also destroyed when vector_new returns.
This is why you see garbage printed by your printf.
Your code has to be completely redesigned with regard to memory management. The actual array has to be allocated dynamically, using malloc. The vector_t object itself might be allocated dynamically or might be declared as a local variable in main and passed to vector_new for initialization. (Which approach you want to follow is up to you).
For example, if we decide to do everything using dynamic allocation, then it might look as follows
vector_t* vector_new(size_t size)
{
vector_t* v = malloc(sizeof *v);
v->size = size;
v->vector = malloc(v->size * sizeof *v->vector);
return v;
}
(and don't forget to check that malloc succeeded).
However, everything that we allocated dynamically we have to deallocate later using free. So, you will have to write a vector_free function for that purpose.
Complete re-write of answer to address your question, and to provide alternate approach:
The code as written in OP will not compile: &v is an illegal return value.
If I modify your code as such:
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t* vector_new(size_t size)
{
int vector[size];
vector_t v, *pV;
pV = &v;
pV->size = size;
pV->vector = vector;
return pV;
}
int main(int argc, char* argv[])
{
vector_t* vec = vector_new(3);
printf("v has size %d.\n", vec->size);
printf("v has size %d.\n", vec->size);
getchar();
return EXIT_SUCCESS;
}
It builds and runs, but returns unintended values for vec->size in main() due to the local scope of that variable in the function vector_new.
Recommend creating globally visible instance of your struct, and redefine vector_new() to int initVector(void):
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
typedef struct
{
size_t size;
int* vector;
} vector_t;
vector_t v, *pV;//globally visible instance of struct
int initVector(void)
{
int i;
pV->size = SIZE;
pV->vector = calloc(SIZE, sizeof(int));
if(!pV->vector) return -1;
for(i=0;i<SIZE;i++)
{
pV->vector[i] = i;
}
return 0;
}
int main(int argc, char* argv[])
{
int i;
pV = &v; //initialize instance of struct
if(initVector() == 0)
{
printf("pV->size has size %d.\n", pV->size);
for(i=0;i<SIZE;i++) printf("pV->vector[%d] == %d.\n", i, pV->vector[i]);
}
getchar(); //to pause execution
return EXIT_SUCCESS;
}
Yields these results:
You still need to write a freeVector function to undo all the allocated memory.
#include <stdio.h>
#include <malloc.h>
main()
{
int arr[5]={1,2,3,4,5};
int brr[5]={6,7,8,9,10};
int *p,*m;
m=&brr[0];
p=&arr[4];
int count=5;
while(count!=0)
{
p++;
*p=*m;
m++;
count--;
}
p=&arr[0];
while(count<=9)
{
printf("%d ",*p);
p++;
count++;
}
return 0;
}
You are trying to write past the end of the array arr, which has undefined behavior.
Instead, you should allocate an array with enough space for the combination of the two arrays, and then write into that instead.
int arr[10]={1,2,3,4,5};
Also, note that memcpy already does what you want, although I assume this is only an exercise.
#include <stdio.h>
#include <malloc.h>
#include <string.h>
main()
{
int arr[10]={1,2,3,4,5};
int brr[5]={6,7,8,9,10};
memcpy(arr + 5, brr, 5*sizeof(int));
return 0;
}
You réserve only 5 ints in arr and write 10. C does no size control in arrays and your code compiles fine. But at runtime, you will overwrite unwanted memory locations. You should have
int arr[10]={1,2,3,4,5};
to reserve enough memory.
Today I'm trying to implement a queue, but one that works with structures within arrays (I've always hated the C 'Array of Structs' terminology, as I am not trying to make that). However, when I try and do a basic initialization, I run into the compiler error as follows.
"Request for member '**' in something not a structure or union. "
Here's my code, not much as of now.
//------------------------Preprocessor Instructions. ------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define MAX 128
#define BUFFER 120
//-------------------------Global Stuff -------------------------------------------------
int head=-1;
int tail=-1; //Starting head and tail at -1.
struct Entry{
int Data;
int Hops;
};
struct Entry Queue[MAX]; //Queue made up of structs.
int visited[MAX];
//------------------------Function Definitions. -----------------------------------------
int QueuePush(struct Entry *q, int num);
int QueuePop(struct Entry *q);
int IsEmpty(struct Entry *q);
//------------------------Main. ---------------------------------------------------------
int main(void)
{
int i;
while(i<MAX){
Queue.Data[i]=0;
Queue.Hops[i]=0;
i++;
}
for(i=0;i<=10;i++){
printf("Queue Data[%d] = %d \n", i, Queue[i].Data);
printf("Queue Hops = %d \n", Queue[i].Hops);
}
}
Am I making some scary, large error in the way I'm defining the array? Or is the issue syntactical? Thanks in advance.
You should write
Queue[i].Data = 0;
Queue[i].Hops = 0;
not
Queue.Data[i] = 0;
Queue.Hops[i] = 0;
In you initialization while loop, you have written Queue.Data[i] instead of Queue[i].Data.
And another thing:
int i;
while(i<MAX){
Queue.Data[i]=0;
Queue.Hops[i]=0;
i++;
}
Here i contains random number and this loop will not work, so you should write int i = 0; or use for instead of while.
I'm trying to implement a stack using array pointer. When the stack is full, it expands twice of its original size. When the number of elements stored in the stack is half size of the stack, it shrinks in half. Push works fine. The problem is pop. When I put testSize in pop, the program crashes (See balded lines). Can anyone help me find me to fix it?
#include <stdio.h>
#include "stack.h"
#include <stdlib.h>
double* initialize(int* top)
{
*top=0;
return (double*)malloc(sizeof(double)*2);
}
// add a new value to the top of the stack (if not full)
void push(double* stack, int* top, const double new_value, int *stack_size)
{
*(stack+*top)=new_value;
++*top;
testSize(stack,stack_size,top);
}
// remove (and return) the value at the top of the stack (if not empty)
double pop(double* stack, int* top,int* stack_size)
{
**//testSize(stack,stack_size,top);**
if(*top)
{
int temp=--*top;
double result= *(stack+temp);
**//testSize(stack,stack_size,top);**
return result;
}
printf("%d top \n",*top);
return 0;
}
void testSize(double *stack, int *stack_size, int * top) //size operation
{
if(*top==*stack_size) //see if it is full
{
stack=(double*)realloc(stack,(*stack_size)*sizeof(double)*2); //expand size reallocate memory
*stack_size=*stack_size*2;
}else if(*top<*stack_size/2)
{
//shrink
}
}
#include <stdlib.h>
#include <stdio.h>
#include "stack.h"
int main(int args, char* argv[])
{
double* my_stack = NULL;
int my_top = 0;
int stack_size=2; //initial dynamic array size
my_stack=initialize(&my_top); //initial size of 2
int p;
for(p=0;p<10;++p)
push(my_stack,&my_top,p+0.1,&stack_size);
pop(my_stack,&my_top,stack_size);
printf("%d elements total \nDynamic current stack size %d \n",my_top,stack_size); //summary
//print stack
int i;
for(i=my_top-1; i>=0; --i)
{
printf("%f \n", *(my_stack+i));
}
free(my_stack);
return 0;
}
This line:
pop(my_stack,&my_top,stack_size);
should be
pop(my_stack,&my_top,&stack_size); /* take address of stack_size with '&' */
I suggest you compile with the -Wall option and look for warnings, then eliminate them. This will not only improve your coding style but help you find this sort of thing quickly.
Your pop() function takes an int* as the 3rd parameter, but you're passing an int in the following line:
pop(my_stack, &my_top, stack_size);
Should be:
pop(my_stack, &my_top, &stack_size);
So in testSize() when you try to de-reference this non-pointer the program crashes.